There are times when you have to use global variables. For example, it is necessary for initialization at the time of testing (I was addicted to this this time) I'll explain the realistic situation I'm addicted to later (probably about 100 people who are addicted to the same thing), but let's take it easy for the time being in a quiz format.
What do you think the output of the main function below is?
package main
import (
"fmt"
)
var global string
func main(){
global = "initial state"
fmt.Println(global)
}
You may hear a voice saying, "Are you stupid?" Just in case the answer is
initial state
is. Then, next is here. (I will omit import from the next time) Please expect the answer, right?
var global string
func main(){
global = "initial state"
global ,err := double()
if err != nil{}
fmt.Println(global)
}
func double()(string,error){
return "double",nil
}
It's still easy. The answer is
double
is.
By the way, is the global
output here really a globally defined global
?
By the way, there is a globally defined * sql.DB
as an example of how to write like this. (I thought that only undefined err would be newly defined if I wrote it this way.)
Next is the main subject.
var global string
func main(){
global = "initial state"
global ,err := double()
if err != nil{}
mistake()
fmt.Println(global)
}
func double()(string,error){
return "double",nil
}
func mistake(){
global = "mistake"
}
Which do you think the answer is, mistake
or double
?
The correct answer is
double
is.
It seems that global
inmistake ()
and global
that used : =
in the main function are treated as different variables. If this happens, is there a way to refer to the global global
from within the main function ...
I feel like I'm in trouble when I'm in a situation like this quiz, but I'm in a very realistic situation.
See the example below. Defines the setUp
function to initialize the * sql.DB
used in the test.
However, in this case, a new Db
is defined only in the setUp
function, which is different from the global Db
, and the global Db
is not updated.
var Db *sql.DB
func TestMain(m *testing.M){
var t *testing.T
setUp(t)
code := m.Run()
tearDown()
os.Exit(code)
}
func setUp(t *testing.T){
Db, err := sql.Open("mysql", "mysql:mysql@/mission")
if err != nil {
t.Error("Error: Could not connect database",err)
}
}
So I have to write like this. (I don't know if it's a best practice.)
var Db *sql.DB
func TestMain(m *testing.M){
var t *testing.T
setUp(t)
code := m.Run()
tearDown()
os.Exit(code)
}
func setUp(t *testing.T){
db, err := sql.Open("mysql", "mysql:mysql@/mission")
if err != nil {
t.Error("Error: Could not connect database",err)
}
Db = db
}
This avoids the problem of newly defining Db
in the Setup function and allows us to use a common Db
throughout the test.
If you don't understand the language specifications, you'll be addicted to it.
Recommended Posts