Need help with Pointers & Structs

Hey. These two structures store the data:

type Collection struct {
    First *Element
    Last  *Element

type Element struct {
	Value int
	Next  *Element

I pass to them in the form:

collection: = Collection {} 
       for i: = 0; i < 5; i ++ { 
              collection.AddToCollection (i) 

func (c *Collection) AddToCollection(Value int) {
      newElement := Element{}
      newElement.Value = Value
      if c.First == nil {
           c.First = &newElement
      } else {
           c.Last.Next = &newElement
      c.Last = &newElement

I do not understand how this works.


Note that the code is not correct, but I will assume it is to explain it.

The first line creates an empty collection. It should in fact be

 collection := &Collection{}

It allocates a bloc of memory for the structure Collector and assign its address to the variable named collector. The {} indicates that no initialization value is given the collector struct. Its member first and last will both have the default value which is nil.

The next line is a loop incrementing i from 0 to 4.
The third line calls the method AddElement of collector. Its parameter is i. It will be thus first called with the parameter 0, then with the parameter 1, etc. and finally called with the value 4.

The method AddElement is defined below.
It will allocate a bloc of memory to hold the Element struct.
The code should be

newElement := &Element{}

The & means that it is the address of the allocated Element struct that is assigned to the newElement variable. The := means that the variable is declared and assigned with the value on its right. It should be

c.First = newElement

The next line assign the argument Value of the method to the field Value of the Element struct. This will be 0, 1, etc. for each call of the method in the above loop.

The field First of the Collector struct is compared against nil. It is nil just after initialization. If it is nil, the address of the allocated Element is assigned to it. Otherwise, it contains the address of another element, and the address of the new element is assigned to c.Last.Next.

This instruction assumes that c.Last is not nil and the address of the last element of a list. The field Next of each of the element of the list contains the address of the next element. It’s called a linked list because elements are chained together. This instruction assigns the new element as the last element of the list. The new element is thus appended to the list. It should be

c.Last.Next = newElement

The last instruction updates the field Last of the Collection so that it holds the address of element we just appended and is now the new last element of the list. It should be

C.Last = newElement

In summary, this code appends elements to the end of a linked list.


Many thanks! Especially for linked list :slight_smile:


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.