Go language error report

problem description

the environmental background of the problems and what methods you have tried

Val is a member variable of TreeNode structure
stack.Peek () the return value is (bool, interface {})

related codes

_, _top := stack.Peek()
// 
// _top = _top.(*TreeNode)
// res = append(res, _top.Val)
// 
res = append(res, _top.(*TreeNode).Val)
// 
_top2 := _top.(*TreeNode)
res = append(res, _top2.Val)

what result do you expect? What is the error message actually seen?

Why do I report an error when I first cast the type of the two lines of code that are commented out, and then go to fetch the Val? The error message is
type interface {} is interface with no methods

Mar.28,2021

the type is wrong. The top from
_, _ top: = stack.Peek () is of interface {} type. There is no problem
_ top = _ top. ( TreeNode) syntax, but remember that _ top is the inteface {} type, and _ top. ( TreeNode)
equals not doing.

so go to the following line
res = append (res, _ top.Val)
_ top is an interface {}, how can there be a Val member variable

change those two lines of code to
_ tmp: = _ top. (* TreeNode)
res = append (res, _ tmp.Val)
then ok

Menu