this is my program.When I run it, it gives the following error - a.sum undefined (type float32 has no field or method sum)
package main
import (
"fmt"
)
type Calculation interface {
operation(input []float32)
}
type Addition struct {
sum float32
}
func (a Addition) operation(input []float32) {
a.sum = input[0]
for _, a := range input[1:] {
a.sum += a
}
fmt.Println("Sum :", a.sum)
}
func main() {
var n int
fmt.Println("Enter the no of inputs : ")
fmt.Scanln(&n)
var input []float32
input = make([]float32 , n)
fmt.Println("Enter the numbers ")
for i:=0 ; i <n ; i++ {
fmt.Scanln(&input[i])
}
var c Calculation
i := Addition{0}
c = i
c.operation(input)
}
I have written 3 more functions Subtraction , Multiplication and Division with Addition. All of them follow similar format but those three run with out any error, Only addition is giving this error. Unable to figure out why.
Your variable a
in the loop shadows the variable a
representing Addition. Changing your loop to this will solve the problem:
for _, v := range input[1:] {
a.sum += v
}