golang为什么没有栈结构?

Invalid operation: i-ind (mismatched types int and interface{})

LeetCode 739实现

golang没有设计stack类型吗?

答案是有的!使用list(双链表)的部分操作就可以达到stack操作的目的。

stack := list.New() //初始化栈
ind := stack.Remove(stack.Front()).(int) //出栈
stack.PushFront(i) //入栈
fmt.Println(stack.Front().Value)

但是为什么需要.(int)的类型断言?给stack传入的本来就是int类型的

// golang list源码
type Element struct {
	next, prev *Element
	list *List
	Value interface{}
}

可以看到Value是 interface{}类型的变量。所以不进行转换调用会报错 会报错因为content是interface{}类型, 而不是int类型(Invalid operation: i-ind (mismatched types int and interface{}))
通过断言实现了类型转换。

参考资料

https://studygolang.com/articles/4276

发布了399 篇原创文章 · 获赞 266 · 访问量 41万+

猜你喜欢

转载自blog.csdn.net/csdn_kou/article/details/105317002
今日推荐