Golang中如何为接口类型添加值
Golang中如何为接口类型添加值
package main
type example interface{
LiterExample() int
}
type nlo interface{
example
}
type new struct{
field1 []nlo
}
func (n new) LiterExample() int{
return n.field1[0].Literlat()
}
func main() {
var forest =new{[]nlo{}}
forest.field1=append(forest.field1, ?)
}
如何向这个切片添加值?我在这个字段处用’?'标记。我无法添加任何内容,例如:字符串、整数或其他数据类型。
更多关于Golang中如何为接口类型添加值的实战教程也可以访问 https://www.itying.com/category-94-b0.html
2 回复
package main
type example interface {
LiterExample() int
}
type nlo interface {
Literlat() int
}
type new struct {
field1 []nlo
}
func (n new) LiterExample() int {
return n.field1[0].Literlat()
}
type nlo2 struct {
}
func (nl nlo2) Literlat() int {
return 0
}
func main() {
var forest = new{}
var wat = nlo2{}
forest.field1 = append(forest.field1, wat)
}
更多关于Golang中如何为接口类型添加值的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
在Golang中,要为接口类型的切片添加值,需要提供实现了该接口的具体类型。根据你的代码,nlo 是一个接口类型,它嵌入了 example 接口。因此,任何实现了 LiterExample() int 方法的类型都可以添加到 forest.field1 切片中。
以下是修改后的示例代码:
package main
import "fmt"
type example interface {
LiterExample() int
}
type nlo interface {
example
}
type new struct {
field1 []nlo
}
// 实现 nlo 接口的具体类型
type concreteType struct {
value int
}
// 实现 LiterExample 方法
func (c concreteType) LiterExample() int {
return c.value
}
func (n new) LiterExample() int {
if len(n.field1) > 0 {
return n.field1[0].LiterExample()
}
return 0
}
func main() {
var forest = new{[]nlo{}}
// 创建 concreteType 实例
c := concreteType{value: 42}
// 添加到切片中
forest.field1 = append(forest.field1, c)
// 验证添加成功
fmt.Println(forest.field1[0].LiterExample()) // 输出: 42
}
关键点:
- 定义了一个具体类型
concreteType,它实现了LiterExample() int方法 - 由于
concreteType实现了example接口,而nlo接口嵌入了example,因此concreteType也隐式实现了nlo接口 - 可以创建
concreteType的实例并将其添加到nlo类型的切片中
你还可以添加其他实现了相同接口的不同类型:
// 另一个实现 nlo 接口的类型
type anotherType struct {
data string
}
func (a anotherType) LiterExample() int {
return len(a.data)
}
func main() {
var forest = new{[]nlo{}}
// 添加不同类型的实例
forest.field1 = append(forest.field1, concreteType{value: 42})
forest.field1 = append(forest.field1, anotherType{data: "hello"})
// 调用接口方法
for _, item := range forest.field1 {
fmt.Println(item.LiterExample())
}
// 输出:
// 42
// 5
}
这样你就可以向接口类型的切片添加任何实现了该接口的具体类型的值。

