dongmei425373 2018-12-21 12:35
浏览 106
已采纳

接口是否只能在Go中由struct数据类型实现?

I'm quite new to Go and was looking at Interfaces and their implementations. All examples I have encountered use struct{} to implement any interface. Is it possible to use any basic type?

  • 写回答

1条回答 默认 最新

  • dongrong9938 2018-12-21 12:41
    关注

    The Go Programming Language Specification

    Method declarations

    A method is a function with a receiver. A method declaration binds an identifier, the method name, to a method, and associates the method with the receiver's base type.

    The receiver is specified via an extra parameter section preceding the method name. That parameter section must declare a single non-variadic parameter, the receiver. Its type must be of the form T or *T (possibly using parentheses) where T is a type name. The type denoted by T is called the receiver base type; it must not be a pointer or interface type and it must be defined in the same package as the method. The method is said to be bound to the base type and the method name is visible only within selectors for type T or *T.


    No. It can be any type other than a pointer or interface type.


    For example, using string as the underlying type,

    package main
    
    import (
        "fmt"
        "strings"
    )
    
    type Caser interface {
        Upper() string
        Lower() string
    }
    
    type Str string
    
    func (s Str) Upper() string {
        return strings.ToUpper(string(s))
    }
    
    func (s Str) Lower() string {
        return strings.ToLower(string(s))
    }
    
    func main() {
        str := Str("Forty-Two")
        fmt.Println(str)
        up := str.Upper()
        fmt.Println(up)
        lo := str.Lower()
        fmt.Println(lo)
    }
    

    Playground: https://play.golang.org/p/9RDRTftqWot

    Output:

    Forty-Two
    FORTY-TWO
    forty-two
    

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

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?