How to fix golang too many arguments error

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

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.

huangapple
  • 本文由 发表于 2017年8月11日 22:56:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/45638189.html
匿名

发表评论

匿名网友

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

确定