can you use a primitive or inbuild data types as a method in golang

huangapple go评论82阅读模式
英文:

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)
}

huangapple
  • 本文由 发表于 2021年6月27日 00:04:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/68144117.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定