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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵