15. Go - Structs
Struct is an aggregate data type that aggregates together values of different types.
Creating struct:
type myStruct struct {
name string
age int
}
Creating a variable using a type struct:
// Using composite literal TYPE{values} to create.
personA := myStruct {
name: "BOB",
age: 32,
}
Accessing fields in a struct:
// Using dot notation
fmt.Println(personA.age,personA.name)
Sample Code:
package main
import "fmt"
// Human Struct
type humanA struct {
gender string
age int
weight float64
}
//
func (a *humanA) printdetail() {
fmt.Printf("Name: Peter\nGender: %s\nAge: %d\nWeight: %g", a.gender, a.age, a.weight)
}
func main() {
var peter = new(humanA)
*peter = humanA{"Male", 30, 50.00}
peter.printdetail()
}
Creating anonymous structs:
// Initializing a struct in a variable and declaring its values at the same time. Used for one time declaration.
peter := struct{
name string
age int
}{
name: "BOB",
age: 32,
}
Comments
Post a Comment