英文:
How to fix golang too many arguments error
问题
我正在使用以下代码:
package main
import (
"fmt"
)
type triangle interface {
area() int
}
type details struct {
height int
base int
}
func (a details) area() int {
s := a.height + a.base
fmt.Println("the area is", s)
return s
}
func main() {
r := details{height: 3, base: 4}
var p1 triangle
p1.area(r)
}
我不明白为什么会出现以下错误:
在调用 p1.area 时参数过多
已有 (details)
需要 ()
我假设 p1 是 triangle 接口的对象,可以带参数调用 area() 方法。不明白为什么会失败。
英文:
i am using following code...
package main
import (
"fmt"
)
type traingle interface {
area() int
}
type details struct {
height int
base int
}
func (a details) area() int {
s := a.height + a.base
fmt.Println("the area is", s)
return s
}
func main() {
r := details{height: 3, base: 4}
var p1 traingle
p1.area(r)
}
not getting why getting following error
> too many arguments in call to p1.area
have (details)
want ()
i am assuming that p1 object of triangle can call area() method with arguments. not getting why it is failing.
答案1
得分: 5
函数area
在其定义中不接受任何参数:
area() int
// ...
func (a details) area() int {
因此,向它传递任何参数都会导致错误,错误提示说的是参数太多。在函数中没有地方使用参数。它基于接收器的属性进行所有计算,而不是任何参数。您还在未初始化(nil)的接口值上调用它。看起来您可能想要的是:
r := details{height: 3, base: 4}
r.area()
英文:
The function area
takes no arguments in its definition:
area() int
// ...
func (a details) area() int {
Therefor, passing any arguments to it is, as the error says, too many arguments. There is nowhere in the function where it makes use of arguments. It's making all its calculations based on the properties of its receiver, not any arguments. You're also calling it on an uninitialized (nil) interface value. It looks like what you want is probably:
r := details{height: 3, base: 4}
r.area()
答案2
得分: 2
请尝试这个代码:
package main
import (
"fmt"
)
type shape interface {
area() int
}
type traingle struct {
height int
base int
}
func (a traingle) area() int {
return a.height * a.base / 2
}
func main() {
var p1 shape = traingle{height: 3, base: 4}
fmt.Println(p1.area())
}
输出结果:
6
并参考这个关于shape的例子:https://stackoverflow.com/a/38818437/8208215
希望对你有帮助。
英文:
Try this:
package main
import (
"fmt"
)
type shape interface {
area() int
}
type traingle struct {
height int
base int
}
func (a traingle) area() int {
return a.height * a.base / 2
}
func main() {
var p1 shape = traingle{height: 3, base: 4}
fmt.Println(p1.area())
}
output:
6
And see this example on shape: https://stackoverflow.com/a/38818437/8208215
I hope this helps.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论