本文主要是介绍Go-struct嵌套初始化与赋值,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
struct嵌套的几种用法。
示例一
package mainimport "fmt"
import "encoding/json"type Point struct {X, Y int
}type Circle struct {Center PointRadius int
}type Wheel struct {Circle CircleSpokes int
}func foo() {var w Wheelw.Circle.Center.X = 8w.Circle.Center.Y = 8w.Circle.Radius = 5w.Spokes = 20fmt.Println("foo(): ", w)
}type Circle2 struct {Point // anonymous fields with a named typeRadius int
}type Wheel2 struct {Circle2Spokes int
}func bar() {var w Wheel2w.X = 18w.Y = 18w.Radius = 15w.Spokes = 120fmt.Println("bar(): ", w)
}type Wheel3 struct {*PointRadius int
}func baz() {var w Wheel3w = Wheel3{&Point{28, 28}, 25}json_string, err := json.Marshal(w)if err != nil {fmt.Println("Error: ", err)} else {fmt.Printf("baz(): %s\n", json_string)}fmt.Printf("baz(): %#v\n", w)}/*
foo(): {{{8 8} 5} 20}
bar(): {{{18 18} 15} 120}
baz(): {"X":28,"Y":28,"Radius":25}
baz(): main.Wheel3{Point:(*main.Point)(0xc04200a340), Radius:25}
*/
func main() {foo()bar()baz()
}
示例二
package mainimport "fmt"type Student struct {name stringage int
}type People struct {Student
}func (people *People) Print() {fmt.Printf("People[name:%s, age:%d]\n", people.name, people.age)
}func PrintStudent(student *Student) {fmt.Printf("Student[name:%s, age:%d]\n", student.name, student.age)
}/*
People[name:Tom, age:3]
People[name:Jerry, age:5]
Student[name:Tom, age:3]
People[name:Tom, age:4]
Student[name:Tom, age:3]
*/
func main() {people := People{}people.name = "Tom"people.age = 3people2 := People{Student{name: "Jerry", age: 5}}people.Print()people2.Print()var student Studentstudent = people.StudentPrintStudent(&student)var people3 People = People{student}people3.age++people3.Print()PrintStudent(&student)
}
这篇关于Go-struct嵌套初始化与赋值的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!