首先,声明一个结构体,如果要将一个函数作为一个结构体的方法,则应该在方法名之前,创建一个结构体的实例
例如
type Student struct{
name string
id int64
}
func (student Student)rename(){
student.name = "test"
}
func (student *Student)rename(){
student.name = "test"
}
结构体可以有两种声明方式,区别在结构体之前有没有*号,这也会导致一些程序运行之后的结果不相同
观察没有的时候,运行时的结果
首先没有符号的,应该是创建的结构体,使用结构的时候,将结构体所创建的对象值进行复制,在函数中使用和更改的值也是对象的值所复制的内容。不会更改结构体的字段值
type Student struct {
name string
sex int
id string
}
func (student Student) rename() {
student.name = "test rename"
}
func main() {
stu := Student{name: "test", sex: 1}
stu.rename()
fmt.Println(stu)
}
由运行之后的结果,可知,调用stu.rename()函数,并没有改变对象name值
type Student struct {
name string
sex int
id string
}
func (student *Student) rename() {
student.name = "testrename"
}
func main() {
stu := Student{name: "test", sex: 1}
stu.rename()
fmt.Println(stu)
}
此时,我们观察到,通过调用stu.rename()函数,更改了name字段值。
通过在函数名之前的带*号,是将结构体的实例通过地址进行传递,但是如果没有符号,只是作为参数进行传参并使用,在函数中所更改的值,也是经过复制的值。并没有更改原对象的值。