Skip to content

Instantly share code, notes, and snippets.

@namsral
Last active September 6, 2016 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save namsral/c4ed7aa6650221146cd1faa8c5ac9748 to your computer and use it in GitHub Desktop.
Save namsral/c4ed7aa6650221146cd1faa8c5ac9748 to your computer and use it in GitHub Desktop.
Example of a getter and setter in a single method
package person_test
import (
"fmt"
"strings"
)
// Person is a modern human with a name.
type Person struct {
name string
}
// Name is both a getter and setter to the name property.
func (p *Person) Name(value ...string) string {
if len(value) > 0 {
p.name = strings.Title(value[len(value)-1])
}
return p.name
}
func ExampleGetSet() {
p := &Person{name: "marie"}
p.Name("anna")
name := p.Name()
fmt.Println(name)
// Output: Anna
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment