SoFunction
Updated on 2025-03-03

Set global variables in Golang and use them in other files

1. Define global variables

In Go, the definition method of global variables is very simple. You just need to define a variable outside the function, and the variable will become a global variable

test/library/utils/

package utils

// Define the global variable ServicePoolvar ServicePool = make(map[string]interface{})

func DemoMethod() {
	(ServicePool)
}

2. ServicePool global variables defined in other files

  • In a file containing global variables, make sure the global variable is declared outside the function so that it becomes a package-level variable
  • In the file where you want to use the global variable, import the package containing the global variable
  • In a file using a global variable, you can directly access the global variable

Note: In Go, if you use the var keyword to define global variables, if you do not useMake function to initialize the variable, it will be assigned a zero value. For numeric type, the zero value is 0; for string type, the zero value is an empty string; for pointer type, the zero value is nil

package test

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"math/rand"
	"net/http"
	"strings"
	"time"
	
	"test/library/utils"
)

func Test(ctx , w , req ) {
	("ctx:", ctx)
	("req:", req)
	("w:", w)
	
	name, ok := ["name"]
	if !ok {
		name = ""
	}
}

This is the article about how to set global variables in Golang and use them in other files. For more information about setting global variables in Golang, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!