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条)

报告相同问题?

悬赏问题

  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面