Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically sized Array in golang? [duplicate]

Tags:

go

I would like to know if there is any way by which I can create dynamically sized array to avoid runtime error in the code below.

Error:

panic: runtime error: index out of range in Go

Code:

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func nextLargerNodes(head *ListNode) []int {

    var a []int
    var pha int
    hNum := 0
    currNode := head
    pha = 0
    for currNode.Next != nil {
        iter := currNode.Next
        hNum = currNode.Val
        //phb = pha + 1
        for(iter.Next != nil){
            if hNum < iter.Val {
                hNum = iter.Val
                break
            } else if hNum == iter.Val{
                hNum = 0
                break
            }

            iter = iter.Next
        }
        a[pha] = iter.Val
        pha++
        hNum = 0
        currNode = currNode.Next
    }
    return a
}
like image 947
Rohit Parab Avatar asked Mar 23 '26 09:03

Rohit Parab


2 Answers

You should use append function.

var a []int

is a slice, you can think of it as a "dynamic array". In order to add elements to it, you should use append method. In your code, you used array semantics.

a = append(a, iter.Val)

You can create your slice with a predefined number of elements if you know upfront how many elements you are going to have in your slice.

a := make([]int, 10)

this will create a slice with 10 elements in it.

like image 161
Vlad Bezden Avatar answered Mar 25 '26 01:03

Vlad Bezden


Go arrays are fixed in size, but thanks to the builtin append method, we get dynamic behavior. The fact that append returns an object, really highlights the fact that a new array will be created if necessary. The growth algorithm that append uses is to double the existing capacity.

numbers := make([]int, 0)
numbers = append(numbers, 1)
numbers = append(numbers, 2)
fmt.Println(len(numbers)) // == 2
like image 32
Surjit R Avatar answered Mar 24 '26 23:03

Surjit R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!