why structure does not implement interface [closed]

耗尽温柔 提交于 2021-02-17 07:16:49

问题


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.

  1. Your function contract for UserInput is Add(rune) but the implementation for NumericInput is Add(interface{}). This is the reason you getting the error
  2. GetValue on UserInput interface, but written as Getvalue

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!