英文:
can you use a primitive or inbuild data types as a method in golang
问题
在Go语言中,内置的数据类型不能直接用作函数的方法。方法必须是自定义类型的接收者。如果你尝试将内置类型用作方法的接收者,会出现错误。你可以创建一个自定义类型,并为该类型定义方法来实现你的需求。
英文:
i wanna know if we are able to use inbuild data types as a method for a func in golang, cause whenever I use it as such, it shows an error
答案1
得分: 3
你可以通过首先使用自己的类型来包装内置类型来定义内置类型的方法,就像这样:
type MyInteger int
func (my MyInteger) Tell() {
fmt.Println("I'm MyInteger with value", my)
}
func main() {
var my MyInteger = 42
my.Tell()
}
你可以在Go Playground上尝试,它将打印:
I'm MyInteger with value 42
如果你想使内置类型实现一个接口,这种方法就很有用。例如,这是MyInteger
如何实现fmt.Stringer
接口:
type MyInteger int
func (my MyInteger) String() string {
return "MyInteger " + strconv.Itoa(int(my))
}
func main() {
var my MyInteger = 42
fmt.Println(my)
}
英文:
You can define methods on built-in types by first wrapping them with your own types, like this:
type MyInteger int
func (my MyInteger) Tell() {
fmt.Println("I'm MyInteger with value", my)
}
func main() {
var my MyInteger = 42
my.Tell()
}
You can try this on the Go Playground, it will print:
I'm MyInteger with value 42
This can be useful if you want to make a built-in type implement an interface. For example, here's how MyInteger
would implement the fmt.Stringer
interface:
type MyInteger int
func (my MyInteger) String() string {
return "MyInteger " + strconv.Itoa(int(my))
}
func main() {
var my MyInteger = 42
fmt.Println(my)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论