Go Structs
An introduction to Go structs
Structs
Go uses structs instead of classes.
A struct defines member variables. To define a function equivalent to a class method, place a receiver such as (variable *StructName), which corresponds to this, before the function name.
package main
import "fmt"
type Person struct {
name string
age int
}
func (p *Person) SetPerson(name string, age int) {
p.name = name
p.age = age
}
func (p *Person) GetPerson() (string, int) {
return p.name, p.age
}
func main() {
var p1 Person
p1.SetPerson("devkuma", 23)
name, age := p1.GetPerson()
fmt.Printf("%s(%d)\n", name, age)
}
Output:
devkuma(23)
Struct members whose names start with an uppercase letter can be accessed from outside the package. Members whose names start with a lowercase letter cannot be accessed from outside the package.
type Person struct {
Name string // accessible outside the package
Age int // accessible outside the package
status int // not accessible outside the package
}
When using a struct, initialize its fields as follows.
a1 := Person{ "devkuma", 26 } // initialize in order
a2 := Person{ name: "devkuma", age: 32 } // initialize by name