结构体方法的定义
package main
import (
"fmt"
)
type Circle struct{
radius float64
}
func (c *Circle) GetArea() float64{
return 3.14 * c.radius * c.radius
}
/**
* 需要修改成指针才能修改对应的值,否则是不可以的
*/
func (c *Circle) SetRadius(radius float64){
c.radius = radius
}
/**
* 这里设置不了该值
*/
func (c Circle) SetRadiusNot(radius float64){
c.radius = radius
}
func main(){
var c1 Circle
c1.radius = 10.00
fmt.Println("圆的面积 = ", c1.GetArea() , "圆的半径 = ",c1.radius)
c1.SetRadius(5)
fmt.Println("SetRadius(5), 圆的面积 = ", c1.GetArea() , "圆的半径 = ",c1.radius)
c1.SetRadiusNot(7)
fmt.Println("SetRadiusNot(7), 圆的面积 = ", c1.GetArea() , "圆的半径 = ",c1.radius)
}
结果
圆的面积 = 314 圆的半径 = 10
SetRadius(5), 圆的面积 = 78.5 圆的半径 = 5
SetRadiusNot(7), 圆的面积 = 78.5 圆的半径 = 5
本文由 创作,采用 知识共享署名4.0 国际许可协议进行许可。本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。最后编辑时间为: 2020/06/23 14:01