Can not use same variable name in different go file

452 Views Asked by At

Here is my first go file:

package main

import (
    "bufio"
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
    "os"
    "strconv"
)

var db13 *sql.DB

then, I create the second go file:

package main

import "database/sql"

var db13 *sql.DB

I got an error saying that: ''db13' redeclared in this package'

Am I miss anything here?

2

There are 2 best solutions below

2
Michael On

both file are in "package main" so if you think about it like they are in the namespace

0
AudioBubble On

They are in same package thus it is not allowed. Also different packages in same directory are not allowed.

db13 declared in first.go can be accessed and used in second.go. No need to declare it again.