dongzhi4498 2017-03-11 05:36
浏览 24
已采纳

如何在界面中使用类型别名

Consider the following program:

package main

import (
    "fmt"
)

type MyMethod func(i int, j int, k int) (string, error)

type MyInterface interface {
  Hello(i int, j int, k int) (string, error)
}

type myMethodImpl struct {}

func (*myMethodImpl) Hello(i int, j int, k int) (string, error) {
   return fmt.Sprintf("%d:%d:%d
", i, j, k), nil
}

func main() {
    var im MyInterface = &myMethodImpl{}
    im.Hello(0, 1, 2)
}

How do I use MyMethod in the interface declaration instead of repeating the method signature?

  • 写回答

1条回答 默认 最新

  • drll85318 2017-03-11 12:49
    关注

    You are mixing two different things here. The one is that you define a type which is a function. When you want that type inside another type you need to use a struct.

    Changing your code to a possible solution 1 (not so idiomatic go):

    type MyMethod func(i int, j int, k int) (string, error)
    
    type myMethodImpl struct {
        Hello MyMethod
    }
    
    var hello MyMethod = func(i int, j int, k int) (string, error) {
        return fmt.Sprintf("%d:%d:%d
    ", i, j, k), nil
    }
    
    func main() {
        im := &myMethodImpl{Hello: hello}
        fmt.Println(im.Hello(0, 1, 2))
    }
    

    https://play.golang.org/p/MH-WOnj-Mu

    The other solution would be to change it to use an interface. That solution is your code just without the type definition of MyMethod. https://play.golang.org/p/nGctnTSwnC

    But what is the difference between?

    If you define a func as a type you need to declare it, when you create a function.

    var hello MyMethod = func(i int, j int, k int) (string, error) {
        return fmt.Sprintf("%d:%d:%d
    ", i, j, k), nil
    }
    

    Now hello has just exactly the type MyMethod. If there would be another type for example:

    type YourMethod func(i int, j int, k int) (string, error)
    

    hello will still just the type MyMethod.

    To define an interface you need a method set. But the type MyMethod is not a method. It is just a function type. So the function type is something different then a method definition. For go it would be the same if you want to define a string as a method.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 调用函数时,无关变量的改变引起函数值的改变
  • ¥15 xy坐标转化为经纬度坐标
  • ¥15 一般三角模糊数的上界值和下届值取中值的多少比较合理?
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥20 Hbase启动失败,无法启动HMaster
  • ¥15 sqpingboot在父模块已经引入了mybatisplus 在子组件不写版本号还是报错
  • ¥20 Lumerical FDTD solutions 中模型的相对阻抗,有效介电常数和有效磁导率的实部和虚部的数据如何获得?
  • ¥100 sql reporting service 远程smtp服务器配置支持
  • ¥15 ppyoloe_r带角度目标检测,loss_cls没法收敛
  • ¥15 淘宝交易指数如何解读,其关联的数据指标是什么