接口是否只能在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?

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