英文:
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{}}
但是我需要将stack指定为foo.Custom结构体的容器,因为我之后需要像这样访问start_row和start_column:
Element := Field_2.Pop()
fmt.Printf("%d \n", Element.start_row)
以下是stack的实现:
package stack
type Stack struct {
top *Element
size int
}
type Element struct {
value interface{}
next *Element
}
// 获取栈的长度
func (s *Stack) Length() int {
return s.size
}
// 将新元素推入栈中
func (s *Stack) Push(value interface{}) {
s.top = &Element{value, s.top}
s.size += 1
}
// 从栈中移除顶部元素并返回其值
// 如果栈为空,则返回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
}
英文:
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 \n", 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
}
答案1
得分: 0
几点说明:
-
Custom
中的所有字段都没有被导出,你不能直接从不同的包中修改它们。 -
你不能以那种方式创建
Foo
,但是由于它是一个数组,你可以简单地使用new_element := &foo.Foo{Field_2: Stack{}}
。
英文:
Few points:
-
all fields in
Custom
are not exported, you can't modify them directly from a different package. -
You can't create
Foo
that way, however since it's an array you can simply just usenew_element := &foo.Foo{Field_2: Stack{}}
.
答案2
得分: 0
当前的stack
包的实现中,没有办法强制规定存储在Element
结构体内的value
的类型。
英文:
With the current implementation of package stack, there is no way to enforce the type of value
that gets stored inside struct Element
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论