为什么结构不实现接口 [英] why structure does not implement interface

查看:59
本文介绍了为什么结构不实现接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这为什么会出错

./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)

这与转到界面

推荐答案

该错误消息为您清楚地说明了这一点:接口期望功能签名为 Add(rune),但 NumericInput 具有 Add(interface {}),这些不相同.

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.

您链接的示例在接口中具有所有方法,并且实现返回float64,函数签名相同.

The example you linked to has all methods in the interface and the implementation returning float64, the function signatures are identical.

如果要处理多种类型而不更改接口本身,则需要一个小的辅助函数来执行类型切换并调用 Add(rune).

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

这篇关于为什么结构不实现接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆