Go语言中的String方法
在go中如果重写了String 方法,那在调用fmt.Println时就会自动去执行String 方法
在fmt中定义了接口
![](https://img.haomeiwen.com/i2107695/8376ddb9886a16aa.png)
![](https://img.haomeiwen.com/i2107695/7915c86ecb8b0b8a.png)
![](https://img.haomeiwen.com/i2107695/079afb552f5948c5.png)
在go中如果定义了静态常量,并且使用了iota时,最好对静态常量设置一个String方法
type State int
const (
Running State = iota
Stopped
Rebooting
Terminated
)
func (s State) String() string {
switch s {
case Running:
return “Running”
case Stopped:
return “Stopped”
case Rebooting:
return “Rebooting”
case Terminated:
return “Terminated”
default:
return “Unknown”
}
}
func main(){
state := Running
fmt.Println(“state”, state) // 未添加String 方法时。输入的为0 添加后输出为"Running"
}
网友评论