A story about Go's global variables and scope

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.

quiz

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 ...

When are you in trouble?

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.

Summary

If you don't understand the language specifications, you'll be addicted to it.

Recommended Posts

A story about Go's global variables and scope
A story about Python pop and append
Global and local variables 2
Local scope and global scope
A story about modifying Python and adding functions
Global and local variables 1
A story about kindergartens, nursery schools, and children's gardens
About Python variables and objects
A refreshing story about Python's Slice
A sloppy story about Python's Slice
A story about using Python's reduce
A story about trying to run JavaScripthon on Windows and giving up.
A story about custom users having a sweet and painful look at Django
A story about remodeling Lubuntu into a Chromebook
A story connecting Slack and google spreadsheets
A story about automating online mahjong (Mahjong Soul) with OpenCV and machine learning
A story about machine learning with Kyasuket
A story about trying to connect to MySQL using Heroku and giving up
The story of manipulating python global variables
A story about a 503 error on Heroku open
About _ and __
A story about trying to install uwsgi on an EC2 instance and failing
A story about cross-compiling a python package for AWS Lambda and deploying it serverless
A story about simple machine learning using TensorFlow
A story about operating a GCP instance from Discord
A story about displaying article-linked ads on Jubatus
Practice applying functions and global variables in Python
A story about implementing a login screen with django
A story about running Python on PHP on Heroku
A story about data analysis by machine learning
About variable scope. .. ..
Getting Started with python3 # 2 Learn about types and variables
A story that Seaborn was easy, convenient and impressed
A story about making 3D space recognition with Python
A story about using Resona's software token with 1Password
A story about predicting exchange rates with Deep Learning
A story about migrating entire Linux disk via SSH
A story about making Hanon-like sheet music with Python
A story about trying a (Golang +) Python monorepo with Bazel
A story about reflecting Discord activity in Slack Status
A story about struggling to loop 3 million ID data
A story about how theano was moved with TSUBAME 2.0
A story about changing the master name of BlueZ
A story about a Linux beginner passing LPIC101 in a week
A story about a Linux beginner putting Linux on a Windows tablet
A story about stumbling through PATH after installing anaconda
[Python] Start a batch file from Python and pass variables.
(Note) A story about creating a question answering system using Spring Boot and machine learning (SVM)
A story about building a PyPI cache server (with Docker) and making me a little happy again
(First post) A story about numerical calculation of influenza and new pneumonia coronavirus with Tensorflow
A story about trying to use cron on a Raspberry Pi and getting stuck in space
A story about porting the code of "Try and understand how Linux works" to Rust
A story about developing a machine learning model while managing experiments and models with Azure Machine Learning + MLflow