user1135541
user1135541

Reputation: 1891

Go Global Variables and Scopes of slices

I am starting out with GO language, and getting an error I cannot figure out. How do I create a global slice that all functions within the module can use? Here is what I have:

package main

import (
    "fmt"
)

type Req struct {
    Req     int
    Name    string
}

var Reqs []Req

func ReadReqs(fp string) {
    var CReq Req;
    CReq.Req = 1
    CReq.Name = "first"
    Reqs := append(Reqs, CReq)
}

func main() {
    Reqs := make([]Req, 0)

    if len(Reqs) > 0 {
        fmt.Println(Reqs[0])
    }

    fmt.Println(Reqs)
}

This code will not compile because of the following error:

./question.go:18: Reqs declared and not used

I was thinking that declaring var Reqs []Req should declare the variable, but it does not seem to be aware of it inside the ReadReqs function. I do realize that globals are BAD but I would like to use global var for this simple program.

Upvotes: 0

Views: 4810

Answers (3)

Marc
Marc

Reputation: 1820

Okay first of all I'd recommend you to read Effective Go before continuing.

You are declaring your global variable using:

var Reqs []Req

Then re-declaring a variable with the same name using:

Reqs := ......

You are declaring two different variables.


var Name type also initializes the variable:

var s string

Is equivalent to:

s := ""

So this makes the following line useless:

Reqs = make([]Req, 0)

You can try your fixed code here (Golang Play).

Upvotes: 3

Mr_Pink
Mr_Pink

Reputation: 109398

You're re-declaring Reqs with the := operator. Drop the colon.

You should probably start with the basics first:

Upvotes: 1

Volker
Volker

Reputation: 42412

With := you are declaring a new variable (not writing to the global) and that new variable at function scope is unused. (Has nothing to do with globals.)

Upvotes: 2

Related Questions