[Translate] Effective go initialization

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Initialization

Although it doesn ' t look superficially very different from initialization in C or C + +, initialization in Go are more powerf Ul. Complex structures can be built during initialization and the ordering issues between initialized objects in different PAC Kages is handled correctly.

On the face of it, the go initialization is not the same as the C + +, but go more complex data structures can be created at initialization time and go can accurately handle object initialization sequences between different packages


CONSTANTS constant Initialization

Constants in Go is just that-constant. They is created at compile time, even if defined as locals in functions, and can is only numbers, strings or booleans. Because of the compile-time restriction, the expressions that define them must is constant expressions, evaluatable by the Compiler. For instance, 1<<3 was a constant expression, while math. Sin (Math. PI/4) is isn't because the function call to math. Sin needs to happen at run time.

Constants in Go are created at compile time even if a variable is a local variable defined within a function, and a constant can only be a numeric string, or a Boolean value is limited to this conditional constant expression must be deduced by the compiler, for example, 1<<3 is a constant expression and math. Sin (Math. PI/4) is not a constant expression because it involves a function call which is evaluated at run time.

In Go, enumerated constants is created using the Iota enumerator. Since Iota can be part of a expression and expressions can be implicitly repeated, it's easy to build intricate sets of Values.

Enumeration constants in go can be created by iota because Iota can be part of an expression and the expression can be repeated easily to create complex datasets every time a const keyword appears iota will be reset to 0 Iota automatically at the next reference +1 when the const assignment expression is the same, the assignment expression Following this example can be omitted after the assignment expression is omitted unified as 1<< (10*iota)

Type ByteSize Float64const (    _           //Ignore first value by assigning to blank identifier KB bytesize = 1 << (iota)    MB    GB    TB    PB    EB    ZB    YB)


The ability to attach a method such as String to a type makes it possible for such values to format themselves automatical ly for printing, even as part of the general type.

In go, you can define methods for most types, such as defining a string method for a type, to output a string representation of a type.

Func (b bytesize) string () string {    switch {case    b >= YB:        return FMT. Sprintf ("%.2fyb", b/yb) case    b >= ZB:        return FMT. Sprintf ("%.2fzb", B/ZB) case    b >= EB:        return FMT. Sprintf ("%.2feb", B/eb) case    b >= PB:        return FMT. Sprintf ("%.2FPB", B/PB) case    b >= TB:        return FMT. Sprintf ("%.2ftb", B/TB) case    b >= GB:        return FMT. Sprintf ("%.2FGB", B/GB) case    b >= MB:        return FMT. Sprintf ("%.2FMB", b/mb) case    b >= KB:        return FMT. Sprintf ("%.2fkb", b/kb)    }    return to FMT. Sprintf ("%.2FB", B)}

The expression YB prints as 1.00YB, while ByteSize (1E13) prints as 9.09TB.

By this function YB can be printed into 1.00YB, while ByteSize (1E13) is printed to 9.09TB

Note that it's fine to call Sprintf and friends in the implementation of String methods, but beware of recurring into the String method through the nested Sprintf call using a string format (%s,%q,%v,%x or%x). The bytesize implementation of String is safe because it calls Sprintf with%f.

You can call sprintf and related output functions when you write a string function, but be careful to prevent sprintf from using the format modifier%s,%q,%v,%x,%x, where ByteSize's string method is safe because only the%f modifier


Variables variable Initialization

Variables can is initialized just like constants but the initializer can is a general expression computed at run time.

Variables can be initialized like constants, but can also be typed at run time by a generic expression.

var (    home   = OS). Getenv ("HOME")    user   = os. Getenv ("USER")    goroot = os. Getenv ("Goroot"))


The INIT function init initialization functions

Finally, each of the source file can define its own niladic the INIT function to set up whatever the state is required. (actually each file can has multiple init functions.) And finally means Finally:init is called after all the variable declarations in the package has evaluated their Initiali Zers, and those is evaluated only after all the imported packages has been initialized.

Each source file can define its own init initialization function (can have more than one init function) init will be called after the initialization of variables in all packages can be compared with other object-oriented constructors the most characteristic subclass is finally initialized and the parent class is first initialized

Besides initializations that cannot being expressed as declarations, a common use of INIT functions are to verify or repair Co Rrectness of the program state before real execution begins.

Init is usually used before the program actually performs validation and fixes the state of the program

Func init () {    if user = = "" {        log. Fatal ("$USER not Set")    }    if home = = "" {        home = "/home/" + USER    }    if goroot = = "" {        Goroot = home + "/go"    }    //Goroot May is overridden by--goroot flag on command line.    Flag. Stringvar (&goroot, "Goroot", Goroot, "Go root directory")}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.