struct-go
path: courses/go-course/struct-go.md
- **fileName**: struct-go
- **Created on**: 2024-08-26 16:51:12
struct in go is using to makeing a types from main types and struct and etc....
example:
type car struct {
make string
model string
doors int
mileage int
}
nested struct example:
type wheel struct {
radius int
material strin
}
type car struct {
mileage int
frontWheel wheel
}
// using struct
myCar := car{}
myCar.frontWheel.radius = 5
another example about how to use struct example:
type user struct {
username string
lastname string
age int
UserWork work
}
type work struct {
salirary int
department string
}
func main() {
us1 := user{"yossef", "sabry", 20, work{2000, "it"}}
fmt.Printf("the user name is %s %s, and age %d\n", us1.username, us1.lastname, us1.age)
fmt.Printf("user work is %s, and salirary %d", us1.UserWork.department, us1.UserWork.salirary)
return
}
# Anonymous Structs in Go Example:
myCar := struct {
make string
model string
} {
make: "tesla",
model: "model 3",
}
- is using for make a struct for using only one time not any one can used it again
another way to write Anonymous structs
type car struct {
make string
model string
doors int
mileage int
// wheel is a field containing an anonymous struct
wheel struct {
radius int
material string
}
}
embedded struct example:
type car struct {
make string
model string
}
type truck struct {
// "car" is embedded, so the definition of a
// "truck" now also additionally contains all
// of the fields of the car struct
car
bedSize int
}
/*
type truck struct {
make string
model string
bedSize int
} //now this the look for using this struct
*/
Embedded vs nested
- Unlike nested structs, an embedded struct's fields are accessed at the top level like normal fields.
- Like nested structs, you assign the promoted fields with the embedded struct in a composite literal.
lanesTruck := truck{
bedSize: 10,
car: car{
make: "toyota",
model: "camry",
},
}
fmt.Println(lanesTruck.bedSize)
// embedded fields promoted to the top-level
// instead of lanesTruck.car.make
fmt.Println(lanesTruck.make)
fmt.Println(lanesTruck.model)
Struct methods in Go
type rect struct {
width int
height int
}
// area has a receiver of (r rect)
// rect is the struct
// r is the placeholder
func (r rect) area() int {
return r.width * r.height
}
var r = rect{
width: 5,
height: 10,
}
fmt.Println(r.area())
// prints 50
continue:interface-go.md
before:err-go.md