2017-11-24 5 views
0

なぜこのコードがビルドできないのかわかりにくいです。./main.go:23:15:無効な型アサーション:bar。(Foo)(ノンインターフェイス型の左のバー)

package main 

import (
    "fmt" 
) 

type Foo interface { 
    Cose() string 
} 

type Bar struct { 
    cose string 
} 

func (b *Bar) Cose() string { 
    return b.cose 
} 

func main() { 
    bar := Bar{ 
     cose: "ciaone", 
    } 
    ii, ok := bar.(Foo) 
    if !ok { 
     panic("Maronn") 
    } 
    fmt.Println(" cose : " + ii.Cose()) 
} 

答えて

2

インターフェイスは逆の操作です - インターフェイスを特定のタイプに変換します。同様に:

package main 

import (
    "fmt" 
) 

type Foo interface { 
    Cose() string 
} 

type Bar struct { 
    cose string 
} 

func (b *Bar) Cose() string { 
    return b.cose 
} 

func main() { 
    bar := Foo(&Bar{ 
     cose: "ciaone", 
    }) 
    ii, ok := bar.(*Bar) 
    if !ok { 
     panic("Maronn") 
    } 
    fmt.Println(" cose : " + ii.Cose()) 
} 

デモ:https://play.golang.org/p/ba7fnG9Rjn

関連する問題