如何将自定义结构放入堆栈然后能够访问所有字段?

How to put custom structure to stack and then be able to access all fields?

我有结构 Foo 字段 Field_1 和 Field_2.

  package foo  
  type Custom struct {
      start_row int
      start_column int
      move_row int
      move_column int
    }

    type Foo struct{
      Field_1 [100]Custom
      Field_2 stack.Stack
    }

如何初始化 Foo?像这样,

new_element := &foo.Foo { [100]foo.Custom{}, stack.Stack {} }

但我需要指定堆栈作为 foo.Custom 结构的容器,因为我需要稍后访问 start_row、start_column 像这样

Element: = Field_2.Pop()
fmt.Printf("%d \n", Element.start_row)

这里是堆栈实现

package stack

type Stack struct {
  top *Element
  size int
}

type Element struct {
  value interface{}
  next *Element
}

// Get length of the stack
func (s *Stack) Length() int {
  return s.size
}

// Push a new element into the stack
func (s *Stack) Push(value interface{}) {
  s.top = &Element{value, s.top}
  s.size += 1
}

// Remove the top element from the stack and return value
// If stack is empty return nil
func (s *Stack) Pop() (value interface{}) {
  if s.size > 0 {
    value, s.top = s.top.value, s.top.next
    s.size -= 1
    return
  }
  return nil
}

几点:

  1. Custom中的所有字段都没有导出,你不能直接从不同的包中修改它们。

  2. 你不能那样创建 Foo,但是因为它是一个数组,你可以简单地使用 new_element := &foo.Foo{Field_2: Stack{}}.

使用当前的包堆栈实现,无法强制存储在结构 Element.

中的 value 的类型