Go 为什么结构不实现接口

Go 为什么结构不实现接口,go,interface,Go,Interface,为什么这是一个错误 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:

为什么这是一个错误

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)
}
这和

错误消息为您详细说明了这一点:接口要求函数签名为
Add(符文)
,但
NumericInput
Add(interface{})
,这两个是不同的

您链接到的示例在接口和实现中包含所有方法,返回float64,函数签名相同


如果您希望在不更改接口本身的情况下处理多个类型,则需要一个小型助手函数来执行类型切换并调用
Add(rune)

代码中几乎没有错误

  • 用户输入的函数契约是
    Add(符文)
    ,但数字输入的实现是
    Add(接口{})
    这就是您出现错误的原因
  • 用户输入界面上的
    GetValue
    ,但写为
    GetValue
  • 下面的链接是修复后的代码


    错误会准确而清晰地告诉您问题所在。你需要什么帮助?
    interface{}
    ist不是“任何类型”的花哨词。它是
    接口{}
    ./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)
    
    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)
    }