当我将外部结构的实例传递给外部结构实现的接口的一部分时,无法访问嵌入式结构

Can't access embedded struct when I pass an instance of my outer structinto a slice of an interface, which the outer struct implements

package main

import (
    "fmt"
)

type shape struct {
    name string
}

type square struct {
    shape
    length int
}

type twoDimensional interface {
    area() int
}

func (s square) area() int {
    return s.length * s.length
}


func main() {
    s1 := square{
        length: 2,
    }
    s1.name = "spongebob"
    
    
    allSquares := []twoDimensional{
        s1,
    }
    
    fmt.Println(allSquares[0].name)
}

这给了我以下错误: ./prog.go:36:27: allSquares[0].name undefined (type twoDimensional has no field or method name)

我对这里发生的事情感到困惑。 type square 嵌入了type shape,type square 也实现了twoDimensional 接口。

如果我将 square 的实例传递到 twoDimensionals 的切片中,为什么我无法再从我的 square 访问文字形状?

接口本身没有.name属性。您需要使用类型断言 allSquares[0].(square) 如下:

package main

import (
    "fmt"
)

type shape struct {
    name string
}

type square struct {
    shape
    length int
}

type twoDimensional interface {
    area() int
}

func (s square) area() int {
    return s.length * s.length
}

func main() {
    s1 := square{
        length: 2,
    }
    s1.name = "spongebob"

    allSquares := []twoDimensional{
        s1,
    }

    fmt.Println(allSquares[0].(square).name)
}