为什么 GoLang 方法会导致编译错误?

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

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().

huangapple
  • 本文由 发表于 2017年7月20日 20:32:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/45214857.html
匿名

发表评论

匿名网友

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

确定