douyu7210 2015-03-17 15:26
浏览 21
已采纳

界面参考显示了奇怪的输出

I am trying to understand Go's interface concept and create following code:

package main

import "fmt"

type Failer interface {
    Error() string
}

type Succer interface {
    Success() string
}

type Result interface {
    Failer
    Succer
}

type Fail struct{}

func (*Fail) Error() string {
    return "Error"
}

type Succ struct{}

func (*Succ) Success() string {
    return "Success"
}

type Combi struct{}

func (*Combi) Error() string {
    return "Error"
}

func (*Combi) Success() string {
    return "Success"
}

func main() {

    var r Result
    var s Succer

    c := &Combi{}
    r = c
    s = c
    fmt.Println(r.Error())
    fmt.Println(s)
}

As output I've got

Error 
Error

Why? I've expect as output error and success, because s it is the interface of type Succer, there is no error return as string. And when I change the main function like this:

func main() {

    var r Result
    var s Succer

    c := &Combi{}
    r = c
    s = c

}

the compiler complain

# command-line-arguments
.\sample1.go:42: r declared and not used
.\sample1.go:43: s declared and not used

Why? I assign variables r and s a reference.

  • 写回答

3条回答 默认 最新

  • doujiang3997 2015-03-17 15:55
    关注

    fmt.Println(s) prints "Error" because error is special-cased in the fmt package

            switch v := p.arg.(type) {
            case error:
                handled = true
                defer p.catchPanic(p.arg, verb)
                p.printArg(v.Error(), verb, depth)
                return
    
            case Stringer:
                handled = true
                defer p.catchPanic(p.arg, verb)
                p.printArg(v.String(), verb, depth)
                return
            }
        }
    

    The fmt package first checks if an object is a Formatter, GoStringer, error, or Stringer , in that order, to obtain a value to print.

    As for your last question, you have to use a variable, not just assign it. Printing them removes the error.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源