Create duplicated package level variable

I get warning in goland when I created same name of package level variable - I created several go files in one directory where each file has a same named variable - but it can still run successfully. so, is this allowed in go to use same variable in different files that are under same directory? I think this is definately not a good practice but wondering what’s actual consequence.

Thanks
James

1 Like

I can’t reproduce, I get a build error:

$ for f in $(\ls *.go); do printf "# File: %s\n" $f; cat $f; done
# File: bar.go
package duplicate

var foo int
# File: foo.go
package duplicate

var foo int
$ go build
# _/tmp/tmp.jpv0KFpdQj
./foo.go:3:5: foo redeclared in this block
	previous declaration at ./bar.go:3:5
$ echo $?
2

So how do you build? Whats the content of the files?

1 Like

there are two files under same directory and still can run and build

package main

import (
	"fmt"
	"runtime"
	_ "runtime"
	"sync"
)

var (
	counter int
	wg sync.WaitGroup
)

func main(){
	wg.Add(2)

	go incCounter(1)
	go incCounter(2)

	wg.Wait()
	fmt.Println("final counter: ", counter)
}

func incCounter(input int){
	defer wg.Done()
	for count := 0; count < 2; count++{
		value := counter
		//do werld thing
		runtime.Gosched()
		value ++
		counter = value
	}
	fmt.Println("done by ", input)
}

2nd file:

package main

import (
	"fmt"
	"runtime"
	"sync"
	"sync/atomic"
	_ "sync/atomic"
)

var (
	counter int32
	wg sync.WaitGroup
)
func main(){
	fmt.Println(runtime.GOMAXPROCS(0))
	fmt.Println(runtime.NumCPU())
	//runtime.GOMAXPROCS(1)
	//fmt.Println(runtime.GOMAXPROCS(0))
	wg.Add(2)

	go incCounter(1)
	go incCounter(2)

	wg.Wait()
	fmt.Println("final counter: ", counter)
	fmt.Println(runtime.GOMAXPROCS(0))
}

func incCounter(input int){
	defer wg.Done()
	//value := counter
	atomic.AddInt32(&counter, 1)
	atomic.AddInt32(&counter, 1)
	//counter++
	//counter++
}
1 Like

main package is different. The different files of that package are distinct.

1 Like

can you explain this a bit, not quite follow you.

1 Like

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