doulang1945 2015-05-08 22:36
浏览 2
已采纳

如何将自定义结构堆叠起来然后可以访问所有字段?

I have struct Foo with fields Field_1 and 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
    }

How can I initialize Foo? Something like this,

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

But I need specify stack as container for foo.Custom struct, because I need to access later start_row, start_column like this

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

Here is stack implementation

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
}
  • 写回答

2条回答 默认 最新

  • dqsp60748 2015-05-08 22:38
    关注

    Few points:

    1. all fields in Custom are not exported, you can't modify them directly from a different package.

    2. You can't create Foo that way, however since it's an array you can simply just use new_element := &foo.Foo{Field_2: Stack{}}.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号