seeker
seeker

Reputation: 29

How to create unfixed length slice in Go

I'm new in Go and I have 2 questions:

1 Let's say we have simple for loop written in C#:

static void Main(string[] args)
    {
        List<int> list = new List<int>();
        for (int i = 1; i < 10000; i++)
        {
            if (i % 5 == 0 && i % 3 == 0)
            {
                list.Add(i);
            }
        }
        foreach (int prime in list)
        {
            System.Console.WriteLine(prime);
        }
        Console.ReadKey();
    }

If I wanted to do the same in Go I'll have to use slices. But how to do that?

  1. Which of variable declaration form is more often used: short form (s:= 3) or long (var s int = 3)?

Upvotes: 1

Views: 2589

Answers (3)

Kiochan
Kiochan

Reputation: 487

For 2)

var foo int = 3 // I want a int variable
bar := foo // bar will be the same type with foo

Upvotes: 0

Sarath Sadasivan Pillai
Sarath Sadasivan Pillai

Reputation: 7091

In Go arrays have their place, but they're a bit inflexible, so you don't see them too often in Go code. Slices, though, are everywhere . They build on arrays to provide great power and convenience.

Slice is not of fixed length. It is flexible .

You may declare an empty slice as following

list := make([]int, 0)
list := []int{}
var list []int

Here is how you may right the above function in go

package main

import (
    "fmt"
)


func main() {
        var list []int
        for i:=0;i<10000;i++ {
            if i %5 == 0 && i % 3 == 0 {
                list = append(list, i)
            }
        } 
        for _, val := range list {
            fmt.Println(val)
        }
}

Here is the play link play

Upvotes: 4

Kare Nuorteva
Kare Nuorteva

Reputation: 1356

1) Create a slice with:

list := make([]int, 0)

Append to a slice with:

list = append(list, i)

2) I think there is no single answer to your second question. It depends on how and where the variable is used.

Upvotes: 2

Related Questions