gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:37:40 24 4
gpt4 key购买 nike

我有一个包含字段 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 {} }

但是我需要指定stack作为foo.Custom struct的容器,因为我需要像这样访问后面的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{}}.

关于syntax - 如何将自定义结构放入堆栈然后能够访问所有字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30133844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com