Jak ustawić i pobrać pola w metodzie struct

Po utworzeniu takiej struktury:

type Foo struct {
    name string
}

func (f Foo) SetName(name string) {
    f.name = name
}

func (f Foo) GetName() string {
    return f.name
}

Jak utworzyć nową instancję Foo, set i uzyskać nazwę? Próbowałem:

p := new(Foo)
p.SetName("Abc")
name := p.GetName()

fmt.Println(name)

Nic nie jest drukowane, ponieważ nazwa jest pusta. Jak więc ustawić i uzyskać pole wewnątrz struktury?

Roboczy plac zabaw

Author: Cirelli94, 2012-08-04

3 answers

Komentarz (i roboczy) przykład:

package main

import "fmt"

type Foo struct {
    name string
}

// SetName receives a pointer to Foo so it can modify it.
func (f *Foo) SetName(name string) {
    f.name = name
}

// Name receives a copy of Foo since it doesn't need to modify it.
func (f Foo) Name() string {
    return f.name
}

func main() {
    // Notice the Foo{}. The new(Foo) was just a syntactic sugar for &Foo{}
    // and we don't need a pointer to the Foo, so I replaced it.
    // Not relevant to the problem, though.
    p := Foo{}
    p.SetName("Abc")
    name := p.Name()
    fmt.Println(name)
}

Przetestuj go i wybierz się na wycieczkę po Go , aby dowiedzieć się więcej o metodach i wskaźnikach oraz podstawach Go.

 129
Author: Moshe Revah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-05 16:05:01

Setery i gettery nie są że idiomatyczne iść. Szczególnie getter dla pola x nie nazywa się GetX ale tylko X. Zobacz http://golang.org/doc/effective_go.html#Getters

Jeśli Ustawiacz nie dostarcza specjalnej logiki, np. logika walidacji, nie ma nic złego w eksportowaniu pole i ani zapewnienie settera, ani gettera metoda. (To po prostu czuje się źle dla kogoś z Podstawy Javy. Ale tak nie jest.)

 27
Author: Volker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-07 08:58:29

Na przykład,

package main

import "fmt"

type Foo struct {
    name string
}

func (f *Foo) SetName(name string) {
    f.name = name
}

func (f *Foo) Name() string {
    return f.name
}

func main() {
    p := new(Foo)
    p.SetName("Abc")
    name := p.Name()
    fmt.Println(name)
}

Wyjście:

Abc
 6
Author: peterSO,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-17 12:02:14