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 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM