知识点golang中零值的概念
整型的零值:0
浮点的零值:0
string的零值:""(字符串空)
byte, rune 的零值:0
数组[len]type的零值为: 长度为 len 每个元素的零值为 type 对应的零值。
例如: var c[4]int 的零值为 [0 0 0 0]
slice、map、channel和指针类型的零值:nil
划重点:
客官请看下面代码:
package main
import "fmt"
type Ball struct {
val int
}
type Person1 struct {
person1 *Ball
}
type Person2 struct {
person2 Ball
}
type Bar interface {
setVal(newVal int)
getVal() int
}
func (b Ball) getVal() int {
return b.val
}
func (b *Ball) setVal(newVal int) {
b.val = newVal
}
func main() {
var person1 Person1
//person1 := &Person1{&Ball{val: 10}}
fmt.Println(person1.person1.getVal())
person1.person1.setVal(1000)
fmt.Println(person1.person1.getVal())
//var person2 Person2
person2 := &Person2{Ball{val: 20}}
fmt.Println(person2.person2.getVal())
person2.person2.setVal(2000)
fmt.Println(person2.person2.getVal())
}
看下效果
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x1091506]
goroutine 1 [running]:
main.main()
网友评论