A LITTLE CORNER OF MY WORLD

Read a few words, keep a little time

Every moment worth recording has a light of its own.

Back to all posts
Learn code

05 - Work's with Structure.

Organize your data by creating some structure in Go.

On this page
  1. Define a new type struct
  2. Declaring them
  3. Kind of self
  4. Function returning structure

Define a new type struct

type Person struct {
	Name string
	Age  int
}

Declaring them

girl := &Person{}

Or shorter with the keyword new

girl := new(Person)

Kind of self

You can define “structure” to create your own type

type Person struct {
	Name string
	Age  int
}

// Function with weird syntax, work like "self" in other language
func (p *Person) SayHello() {
	fmt.Println("Hello", p.Name)
}

func main() {
	// use pointer with struct
	girl := new(Person)
	girl.Name = "Alice"
	girl.SayHello()
}

Function returning structure

You can create structure, generating them in function and returning to your main():

$EDITOR pkg/person/check.go
package person

type MyPerson struct {
  Name string
  Age int
}
func Build() (*MyPerson, error) {
  newperson := &MyPerson{} // same with new(MyPerson)
  newperson.Name = "Bob"
  newperson.Age = 10
  return newperson, nil
}
$EDITOR cmd/<name>/main.go
func main() {
  myPerson, err := person.Build()
  if err != nil {
    fmt.Println(err)
	os.Exit(1)
  }
  fmt.Println(myPerson.Name)
  fmt.Println(myPerson.Age)
}
✿

Thank you for reading. I hope these words were useful.

Szorfein
Szorfein / Author

A little code, a little everyday life. Say hello in the guestbook. Guestbook