Go is a typed programming language which means that the compiler always want to know what the type is for every value in program.
Struct types are declared by composing a fixed set of unique fields. Each field in a struct is declared with a known type, which could be a built-in type or another user- defined type.
01 // user defines a user in the program.
02 type user struct {
03 name string
04 email string
05 ext int
06 privileged bool
07 }
Declaration of a new type based on an built-in type
//
type Duration int64
Methods in Go is like methods in OOP programming language like JAVA, it’s add a behaviour to a specific user defined type, so it’s like a manipulator to a suer defined type.
See the example below:
package main
import (
"fmt"
)
type user struct {
name string
email string
}
func (u user) notify() {
fmt.Printf("Sending User Email to %s<%s>\\n", u.name, u.email)
}
func (u *user) changeEmail (email string) {
u.email = email
}
// the parameter between the keyword func and the function name is called a receiver
// and binds the function to the specified type.
// when a function has a reciever, it called method
func main() {
bill := user{"Bill", "bill@email.com"}
bill.notify()
// for the changeEmail method declared with pointer reciever but
// you can use it with value reciever
// Go underneath code perform the following operation
(&bill).notify()
lisa := &user{"Lisa", "lisa@email.com"}
lisa.notify()
bill.changeEmail("bill@newdoamin.com")
bill.notify()
lisa.changeEmail("lisa@comcast.com")
lisa.notify()
// the operation above is equivalent to the next operation
// Go handle this underneath
(*lisa).notify()
}
In Go there are many types to deal with while working with the language:
let’s start with first data types: