Saturday, 15 March 2014

go - Interface reference shows weird output -


I am trying to understand the interface concept of Go and am making the following code:

  Package main import "Fmt" type Failer interface {error (string)} type succer interface {success (string)} type result interface {Failer succer} type unsuccessful structure {} func (* failed) error {} string {return} "Error"} type succ ({combi} string {return "error"} funk (* combi) success () string {return} succeeded The "main") phenque (main {) sar s: c: = & amp; combi {} r = cs = cfmt.printline (r.array) FMT printline (s)}   

Why me? As an output

  error error  

I have been expected to output error and success, because < Code> s is the type of interface, there is no error in the form of a string, and when I change the main function like this:

  func main () {var r result var s succer c: = & amp; combi {} r = cs = c}  

compiler complaint

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

Why? I provide variable r and s context.

< fmt.println (s) print "error" because error < There is a special episode in the / code> 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 .org, verb) p.printArg (v.String (), verb, depth)}}  

fmt package first checks that if the object is < Code> Formatter , GoStringer , error , or stranger , in that order, get a value to print for.

For your last question, you have to use a variable, not just to specify it, it prints out an error.


No comments:

Post a Comment