英文:
Why GoLang Method gives Compile Error?
问题
我正在尝试使用Go语言中的方法。我是一个新手,如果我问了愚蠢的问题,请纠正我。
链接中说我们可以将方法写成普通函数。但是当我尝试以下代码时,它给我编译错误:
a.sq undefined (type MyFloat has no field or method sq)
尽管以下代码中的注释行按预期工作。
请帮助我。以下是我的代码:
package main
import (
"fmt"
)
type MyFloat float64
func sq(f MyFloat) string {
return fmt.Sprintln("The square is: ", f*f)
}
/*func (f MyFloat) sq() string {
return fmt.Sprintln("The square is: ", f*f)
}*/
func main() {
a := MyFloat(2.0)
fmt.Println(sq(a))
}
英文:
I am a trying the Methods in GoLang. I am a newbie so please correct me if I am asking dumb question.
The link says that we can write the Methods as normal Functions. But when I try following code it gives me compile error as
a.sq undefined (type MyFloat has no field or method sq)
The commented lines in following code are working as expected though.
Please help me. Following is my code:
package main
import (
"fmt"
)
type MyFloat float64
func sq (f MyFloat) string {
return fmt.Sprintln("The square is: ", f*f)
}
/*func (f MyFloat) sq() string {
return fmt.Sprintln("The square is: ", f*f)
}*/
func main() {
a := MyFloat(2.0)
fmt.Println(a.sq())
}
答案1
得分: 2
你将 sq
声明为一个函数,而不是一个方法。如果你想将 sq
附加到 MyFloat
上,你应该像这样声明它:
func (f MyFloat) sq() string {
return fmt.Sprintln("The square is: ", f*f)
}
这样你就可以使用 a.sq()
。
英文:
You are declaring sq
as a function, not a method. If you want to attach sq
to MyFloat
, you should declare it like:
func (f MyFloat) sq() string {
return fmt.Sprintln("The square is: ", f*f)
}
This way you will be able to do a.sq()
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论