How to set and get fields in struct's method

StructGetSetGo

Struct Problem Overview


After creating a struct like this:

type Foo struct {
	name string
}

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

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

How do I create a new instance of Foo and set and get the name? I tried the following:

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

fmt.Println(name)

Nothing gets printed, because name is empty. So how do I set and get a field inside a struct?

Working playground

Struct Solutions


Solution 1 - Struct

Commentary (and working) example:

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)
}

Test it and take A Tour of Go to learn more about methods and pointers, and the basics of Go at all.

Solution 2 - Struct

Setters and getters are not that idiomatic to Go. Especially the getter for a field x is not named GetX but just X. See http://golang.org/doc/effective_go.html#Getters

If the setter does not provide special logic, e.g. validation logic, there is nothing wrong with exporting the field and neither providing a setter nor a getter method. (This just feels wrong for someone with a Java background. But it is not.)

Solution 3 - Struct

For example,

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)
}

Output:

Abc

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnopeView Question on Stackoverflow
Solution 1 - StructZippoView Answer on Stackoverflow
Solution 2 - StructVolkerView Answer on Stackoverflow
Solution 3 - StructpeterSOView Answer on Stackoverflow