问题
package main
import (
"fmt"
)
type UserInput interface {
Add(rune)
GetValue() string
}
type NumericInput struct {
input string
}
func (u NumericInput) Add(x interface{}) {
switch v := x.(type) {
case int:
fmt.Println("int:", v)
case float64:
fmt.Println("float64:", v)
case int32:
fmt.Println("int32:", v)
fmt.Println(u.input)
//u.input+x
default:
fmt.Println("unknown")
}
}
func (u NumericInput) Getvalue() string {
return u.input
}
func myfunction(u UserInput) {
u.Add('1')
u.Add('a')
input.Add('0')
fmt.Println(u.GetValue())
}
func main() {
n := NumericInput{}
myfunction(n)
}
why this is giving error
./prog.go:39:15: cannot use n (type NumericInput) as type UserInput in argument to myfunction:
NumericInput does not implement UserInput (wrong type for Add method)
have Add(interface {})
want Add(rune)
this is same as go interfaces
回答1:
The error message spells it out for you: the interface expects a function signature of Add(rune)
but NumericInput
has Add(interface{})
, these are not the same.
The example you linked to has all methods in the interface and the implementation returning float64, the function signatures are identical.
If you want to handle multiple types without changing the interface itself, you'll need a small helper function that performs the type switch and calls Add(rune)
.
回答2:
There are few errors on your code.
- Your function contract for UserInput is
Add(rune)
but the implementation for NumericInput isAdd(interface{})
. This is the reason you getting the error GetValue
on UserInput interface, but written asGetvalue
Below link is the code after being fixed
https://play.golang.org/p/HdCm0theZab
package main
import "fmt"
type UserInput interface {
Add(interface{})
GetValue() string
}
type NumericInput struct {
input string
}
func (u NumericInput) Add(x interface{}) {
switch v := x.(type) {
case int:
fmt.Println("int:", v)
case float64:
fmt.Println("float64:", v)
case int32:
fmt.Println("int32:", v)
fmt.Println(u.input)
//u.input+x
default:
fmt.Println("unknown")
}
}
func (u NumericInput) GetValue() string {
return u.input
}
func myfunction(u UserInput) {
u.Add('1')
u.Add('a')
u.Add('0')
fmt.Println(u.GetValue())
}
func main() {
n := NumericInput{}
myfunction(n)
}
来源:https://stackoverflow.com/questions/61699774/why-structure-does-not-implement-interface