c++结构体定义和使用_[day day go]结构体amp;给结构定义方法
生活随笔
收集整理的這篇文章主要介紹了
c++结构体定义和使用_[day day go]结构体amp;给结构定义方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
結構體
//定義 type treeNode struct {value intleft, right *treeNode }//工廠函數創建 func createNode(value int) *treeNode {return &treeNode{value: value} //這里返回的是局部變量的地址給外部使用(在go這樣子可以的) }func main() {var root treeNodefmt.Println(root)//創建root = treeNode{value: 3}root.left = &treeNode{}root.right = &treeNode{5, nil, nil}root.right.left = new(treeNode)fmt.Println("root:",root)fmt.Println("root.right:",root.right)fmt.Println("root.right.left:",root.right.left)nodes := []treeNode{{value: 3},{},{6, nil, &root},}fmt.Println("nodes:",nodes)root.left = createNode(2)fmt.Println("createNode:",root) } {0 <nil> <nil>} root: {3 0xc00007c060 0xc00007c080} root.right: &{5 0xc00007c0a0 <nil>} root.right.left: &{0 <nil> <nil>} nodes: [{3 <nil> <nil>} {0 <nil> <nil>} {6 <nil> 0xc00007c020}] createNode: {3 0xc00007c060 0xc00007c080}- go僅支持封裝,不支持繼承和多態
- 結構體的創建:不論地址還是結構本身,一律使用.來訪問成員
- 結構體放在堆還是棧是由go的運行機制以及環境決定的,編程者不用關心
給結構定義方法
func (node treeNode) print() {fmt.Print("這是結構體方法打印出來的:",node.value) }func (node *treeNode) setValue(value int) {if node == nil {fmt.Println("setting value to nil node")return}node.value = value }//值不會變 // func (node treeNode) setValue(value int) { // node.value = value // }func (node *treeNode) setValue(value int) {node.value = value } root.print()fmt.Println("nsetValuen")root.right.left.setValue(9)root.right.left.print() 這是結構體方法打印出來的:3 setValue這是結構體方法打印出來的:9func(【結構體】) 【函數名】(){}- func后面括號的是方法接收者(其實就跟函數的返回值一樣)
- 只有使用指針才可以改變結構的內容
- nil指針也可以調用方法(可以將值傳進來,但是nil的賦值會報錯,需要做return處理)
總結
以上是生活随笔為你收集整理的c++结构体定义和使用_[day day go]结构体amp;给结构定义方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: logistic回归 简介_金融专业进!
- 下一篇: python优秀程序员条件_Python