./main.go:23:15: invalid type assertion: bar.(Foo) (non-interface type Bar on left)

Viewed 3889

I've some trouble to understand why this code cant build.

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 Answers

Interface is an opposite operation - converting interface to specific type. Like:

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())
}

Demo: https://play.golang.org/p/ba7fnG9Rjn

Type Assertions for you case, works through the Closures:

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 := func(bar interface{}) Foo {
        ii, ok := bar.(Foo)
        if !ok {
            panic("Maronn")
        }
        return ii
    } (bar)

    fmt.Println(" cose : " + ii.Cose()  )
}
Related