1. 程式人生 > >init functions in Go

init functions in Go

init functions in Go

Identifier main is ubiquitous. Every Go program starts in a package main by calling identically named function. When this function returns the program ends its execution. Functions init also play special role and this post will describe their properties and introduce how to use them.

init functions are defined in package block and are used for:

  • variables initialization if cannot be done in initialization expression,
  • checking / fixing program’s state,
  • registering,
  • running one-time computations,
  • and many more.

Besides some differences discussed below you can put there anything which is valid

inside regular function.

Package initialization

To use a imported package it needs to be initialized first. It’s done by Golang’s runtime system and consists of (order matters):

  1. initialization of imported packages (recursive definition)
  2. computing and assigning initial values for variables declared in a package block
  3. executing init functions inside the package
Package initialization is done only once even if package is imported many times.

The order

Package in Go can contain many files. What is the order of variables initialization and init functions calls if they’re spread across many package’s files? First, initialization dependency machinery kicks in (more in “Initialization dependencies in Go”). When this done there needs to be a decision made if initialize variables in file a.go or maybe z.go shouldbe handled earlier. This depends on the order of files presented to the compiler. If z.go is first passed by build system then variables initializations are done there before doing the same in a.go. The same applies to triggering init functions. Language specification recommends to always use the same order and pass file names from package in lexical order:

To ensure reproducible initialization behavior, build systems are encouraged to present multiple files belonging to the same package in lexical file name order to a compiler.

but relying on particular order is rather a path for less portable programs. Let’s see an example how it all works together:

sandbox.go

package main
import "fmt"
var _ int64 = s()
func init() {
fmt.Println("init in sandbox.go")
}
func s() int64 {
fmt.Println("calling s() in sandbox.go")
return 1
}
func main() {
fmt.Println("main")
}

a.go

package main
import "fmt"
var _ int64 = a()
func init() {
fmt.Println("init in a.go")
}
func a() int64 {
fmt.Println("calling a() in a.go")
return 2
}

z.go

package main
import "fmt"
var _ int64 = z()
func init() {
fmt.Println("init in z.go")
}
func z() int64 {
fmt.Println("calling z() in z.go")
return 3
}

Program outputs:

calling a() in a.go
calling s() in sandbox.go
calling z() in z.go
init in a.go
init in sandbox.go
init in z.go
main

Properties

init function doesn’t take arguments neither returns any value. In contrast to main, identifier init is not declared so cannot be referenced:

package main
import "fmt"
func init() {
fmt.Println("init")
}
func main() {
init()
}

and it gives “undefined: init” error while compilation.

Formally speaking initidentifier doesn’t introduce binding. In the same way works blank identifier represented by underscore character.

相關推薦

init functions in Go

init functions in GoIdentifier main is ubiquitous. Every Go program starts in a package main by calling identically named function. When this function retu

"First Class Functions in Go"

30 June 2011 Programmers new to Go are often surprised by its support for function types, functions as value

Const member functions in C++

pear treat not rul automatic man sel cannot example Recently, I‘ve started to review and learn C++ techniques. During the learning proces

理解golang反射(reflection in Go)

golang reflect golang反射 go反射機制 反射(reflection)是指在運行時,動態獲取程序結構信息(元信息)的一種能力,是靜態類型語言都支持的一種特性,如Java, golang等。這裏主要詳細介紹golang reflection相關知識類型與接口(Types and

[TypeScript] Define Custom Type Guard Functions in TypeScript

nal ria console tro res one inf arr asp One aspect of control flow based type analysis is that the TypeScript compiler narrows the type o

除錯經驗——如何檢視Oracle自定義函式 (How to view definition of user defined functions in Oracle)

問題描述: 現有的Query中似乎使用了一個自定義函式String_to_list,為了排查問題,需要檢視這個函式的定義。 方法:   --新建的function,並未儲存在All_ojbects表中,而是儲存在user_objects表中 SELECT * FRO

Context propagation over HTTP in Go

https://medium.com/@rakyll/context-propagation-over-http-in-go-d4540996e9b0 Context propagation over HTTP in Go Go 1.7 introduced a built-in

Yet another tool to mock interfaces in Go

Yet another tool to mock interfaces in Go https://itnext.io/yet-another-tool-to-mock-interfaces-in-go-73de1b02c041 As a powerful tool, uni

Downloading large files in Go

package main import ( "fmt" "github.com/cavaliercoder/grab" "time" ) func download(dst string,urls ...string) { n:=len(urls) re,err:=grab.Get

How I organize my applications in Go[轉]

Overview For me, the hardest part of learning Go was in structuring my application. Prior to Go, I was working on a Rails applicat

[Bash] Understand and Use Functions in Bash

n this lesson, we'll go over how bash functions work. Bash functions work like mini bash scripts--you can pass parameters and invoke them just like

Table-valued functions and Scalar-valued functions in SQL Server

As the name suggests: table-valued returns table, however Scalar-valued returns a single value, such as a string, integer, or bit value. 1、table-valued fu

Declaring functions in JSP?

You need to enclose that in <%! %> as follows: <%! public String getQuarter(int i){ String quarter; switch(i){ case 1: quarter = "W

Variadic function in Go

What is a variadic function?As we have seen in a functions lesson, a function is a piece of code dedicated to do a particular job. A function takes one or

How big is an int in Go?

How big is an int in Go?Go has several built-in numeric types, “sets of integer or floating-point values.” Some architecture-independent types are uint8 (8

Listeners with several functions in Kotlin. How to make them shine?

One question I get often is how to simplify the interaction with listeners that have several functions on Kotlin. For listeners (or any interfaces) w

5 advanced testing techniques in Go · Segment Blog

Go has a robust built-in testing library.  If you write Go, you already know this.  In this post we will discuss a handful of strategies to level up your G

Using Parser Combinators in Go

Using Parser Combinators in GoLet’s parse in Golang!How would you write a parser for the following calculator grammar?Digit := "0" | "1" | "2" | "3" | "4"

This Blogpost Deploys Servers in Go, NodeJS, Ruby, Python, Java, PHP

This Blogpost Deploys Servers in Go, NodeJS, Ruby, Python, Java, PHPRunning the embeded Repl.it code in this post will live-deploy simple http servers for

Tinyterm: A silly terminal emulator written in Go

This post is about Tinyterm, a silly hack that I presented as a lightning talk at last month’s Sydney Go User group 1. You can find the original slide