user2315104
user2315104

Reputation: 2730

How to fix golang too many arguments error

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.

Upvotes: 1

Views: 12097

Answers (2)

wasmup
wasmup

Reputation: 16283

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.

Upvotes: 2

Adrian
Adrian

Reputation: 46602

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

Upvotes: 5

Related Questions