本文主要是介绍go const(常量),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
常量介绍
示例
package mainimport ("fmt"
)func main() {const name = "tom"fmt.Println(name)const tax float64 = 0.8fmt.Println(tax)
}
go run const.go
tom
0.8
package mainimport ("fmt"
)func main() {const a intfmt.Println(a)
}
go run const.go
# command-line-arguments
./const.go:8:8: missing init expr for a
package mainimport ("fmt"
)func getVal() {fmt.Printf("测试")
}
func main() {const b = 9 / 3fmt.Println(b)//const c = getVal()//fmt.Println(c)
}
go run const.go
3
package mainimport ("fmt"
)func getVal() {fmt.Printf("测试")
}
func main() {//const b = 9 / 3//fmt.Println(b)const c = getVal()fmt.Println(c)
}
go run const.go
# command-line-arguments
./const.go:13:12: getVal() (no value) used as value
package mainimport ("fmt"
)func getVal() {fmt.Printf("测试")
}
func main() {//const b = 9 / 3//fmt.Println(b)//const c = getVal()//fmt.Println(c)num := 9const b = num / 3fmt.Println(b)
}
go run const.go
# command-line-arguments
./const.go:16:12: num / 3 (value of type int) is not constant
常量比较简单的写法
package mainimport ("fmt"
)func getVal() {fmt.Printf("测试")
}
func main() {const (a = 1b = 2)fmt.Println(a, b)const (c = iotade)fmt.Println(c, d, e)
}
go run const.go
1 2
0 1 2
这篇关于go const(常量)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!