Text file tour/basics.article

     1  Packages, variables, and functions.
     2  Learn the basic components of any Go program.
     3  
     4  The Go Authors
     5  https://golang.org
     6  
     7  * Packages
     8  
     9  Every Go program is made up of packages.
    10  
    11  Programs start running in package `main`.
    12  
    13  This program is using the packages with import paths `"fmt"` and `"math/rand"`.
    14  
    15  By convention, the package name is the same as the last element of the import path. For instance, the `"math/rand"` package comprises files that begin with the statement `package`rand`.
    16  
    17  #appengine: *Note:* The environment in which these programs are executed is
    18  #appengine: deterministic, so each time you run the example program
    19  #appengine: `rand.Intn` will return the same number.
    20  #appengine:
    21  #appengine: (To see a different number, seed the number generator; see [[/pkg/math/rand/#Seed][`rand.Seed`]].
    22  #appengine: Time is constant in the playground, so you will need to use something else as the seed.)
    23  
    24  .play basics/packages.go
    25  
    26  * Imports
    27  
    28  This code groups the imports into a parenthesized, "factored" import statement.
    29  
    30  You can also write multiple import statements, like:
    31  
    32  	import "fmt"
    33  	import "math"
    34  
    35  But it is good style to use the factored import statement.
    36  
    37  .play basics/imports.go
    38  
    39  * Exported names
    40  
    41  In Go, a name is exported if it begins with a capital letter.
    42  For example, `Pizza` is an exported name, as is `Pi`, which is exported from
    43  the `math` package.
    44  
    45  `pizza` and `pi` do not start with a capital letter, so they are not exported.
    46  
    47  When importing a package, you can refer only to its exported names.
    48  Any "unexported" names are not accessible from outside the package.
    49  
    50  Run the code. Notice the error message.
    51  
    52  To fix the error, rename `math.pi` to `math.Pi` and try it again.
    53  
    54  .play basics/exported-names.go
    55  
    56  * Functions
    57  
    58  A function can take zero or more arguments.
    59  
    60  In this example, `add` takes two parameters of type `int`.
    61  
    62  Notice that the type comes _after_ the variable name.
    63  
    64  (For more about why types look the way they do, see the [[https://blog.golang.org/gos-declaration-syntax][article on Go's declaration syntax]].)
    65  
    66  .play basics/functions.go
    67  
    68  * Functions continued
    69  
    70  When two or more consecutive named function parameters share a type, you can omit the type from all but the last.
    71  
    72  In this example, we shortened
    73  
    74  	x int, y int
    75  
    76  to
    77  
    78  	x, y int
    79  
    80  .play basics/functions-continued.go
    81  
    82  * Multiple results
    83  
    84  A function can return any number of results.
    85  
    86  The `swap` function returns two strings.
    87  
    88  .play basics/multiple-results.go
    89  
    90  * Named return values
    91  
    92  Go's return values may be named. If so, they are treated as variables defined at the top of the function.
    93  
    94  These names should be used to document the meaning of the return values.
    95  
    96  A `return` statement without arguments returns the named return values. This is known as a "naked" return.
    97  
    98  Naked return statements should be used only in short functions, as with the example shown here. They can harm readability in longer functions.
    99  
   100  .play basics/named-results.go
   101  
   102  * Variables
   103  
   104  The `var` statement declares a list of variables; as in function argument lists, the type is last.
   105  
   106  A `var` statement can be at package or function level. We see both in this example.
   107  
   108  .play basics/variables.go
   109  
   110  * Variables with initializers
   111  
   112  A var declaration can include initializers, one per variable.
   113  
   114  If an initializer is present, the type can be omitted; the variable will take the type of the initializer.
   115  
   116  .play basics/variables-with-initializers.go
   117  
   118  * Short variable declarations
   119  
   120  Inside a function, the `:=` short assignment statement can be used in place of a `var` declaration with implicit type.
   121  
   122  Outside a function, every statement begins with a keyword (`var`, `func`, and so on) and so the `:=` construct is not available.
   123  
   124  .play basics/short-variable-declarations.go
   125  
   126  * Basic types
   127  
   128  Go's basic types are
   129  
   130  	bool
   131  
   132  	string
   133  
   134  	int  int8  int16  int32  int64
   135  	uint uint8 uint16 uint32 uint64 uintptr
   136  
   137  	byte // alias for uint8
   138  
   139  	rune // alias for int32
   140  	     // represents a Unicode code point
   141  
   142  	float32 float64
   143  
   144  	complex64 complex128
   145  
   146  The example shows variables of several types,
   147  and also that variable declarations may be "factored" into blocks,
   148  as with import statements.
   149  
   150  The `int`, `uint`, and `uintptr` types are usually 32 bits wide on 32-bit systems and 64 bits wide on 64-bit systems.
   151  When you need an integer value you should use `int` unless you have a specific reason to use a sized or unsigned integer type.
   152  
   153  .play basics/basic-types.go
   154  
   155  * Zero values
   156  
   157  Variables declared without an explicit initial value are given their
   158  _zero_value_.
   159  
   160  The zero value is:
   161  
   162  - `0` for numeric types,
   163  - `false` for the boolean type, and
   164  - `""` (the empty string) for strings.
   165  
   166  .play basics/zero.go
   167  
   168  * Type conversions
   169  
   170  The expression `T(v)` converts the value `v` to the type `T`.
   171  
   172  Some numeric conversions:
   173  
   174  	var i int = 42
   175  	var f float64 = float64(i)
   176  	var u uint = uint(f)
   177  
   178  Or, put more simply:
   179  
   180  	i := 42
   181  	f := float64(i)
   182  	u := uint(f)
   183  
   184  Unlike in C, in Go assignment between items of different type requires an
   185  explicit conversion.
   186  Try removing the `float64` or `uint` conversions in the example and see what happens.
   187  
   188  .play basics/type-conversions.go
   189  
   190  * Type inference
   191  
   192  When declaring a variable without specifying an explicit type (either by using the `:=` syntax or `var`=` expression syntax), the variable's type is inferred from the value on the right hand side.
   193  
   194  When the right hand side of the declaration is typed, the new variable is of that same type:
   195  
   196  	var i int
   197  	j := i // j is an int
   198  
   199  But when the right hand side contains an untyped numeric constant, the new variable may be an `int`, `float64`, or `complex128` depending on the precision of the constant:
   200  
   201  	i := 42           // int
   202  	f := 3.142        // float64
   203  	g := 0.867 + 0.5i // complex128
   204  
   205  Try changing the initial value of `v` in the example code and observe how its type is affected.
   206  
   207  .play basics/type-inference.go
   208  
   209  * Constants
   210  
   211  Constants are declared like variables, but with the `const` keyword.
   212  
   213  Constants can be character, string, boolean, or numeric values.
   214  
   215  Constants cannot be declared using the `:=` syntax.
   216  
   217  .play basics/constants.go
   218  
   219  * Numeric Constants
   220  
   221  Numeric constants are high-precision _values_.
   222  
   223  An untyped constant takes the type needed by its context.
   224  
   225  Try printing `needInt(Big)` too.
   226  
   227  (An `int` can store at maximum a 64-bit integer, and sometimes less.)
   228  
   229  .play basics/numeric-constants.go
   230  
   231  * Congratulations!
   232  
   233  You finished this lesson!
   234  
   235  You can go back to the list of [[/tour/list][modules]] to find what to learn next, or continue with the [[javascript:click('.next-page')][next lesson]].
   236  

View as plain text