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

我有带有字段 Field_1 和 Field_2 的结构 Foo。


  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

}


繁星coding
浏览 225回答 2
2回答

慕村9548890

对于包堆栈的当前实现,无法强制执行valuestruct 中存储的类型Element。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go