Table of Contents
- Declare Variables
- Scoping and Lifetime of Variables
- About Pointers
- Can I use
++i, instead of
Declare Variables howto
var name type = expression
There is also a concise syntax called Short Variable Declarations:
name := expression
- Keep in mind that
:=is a declaration, whereas
=is an assignment.
:=does not necessarily declare all the variables on its left-hand side
new Function discussion
new(T)returns a value of type
Following two functions are equivalent:
new(T) for types with no data, such as
new() will return the same addresses between multiple calls. Otherwise, it will allocate memory for each call.
Scoping and Lifetime of Variables discussion
- Package-level variables
- Visible not only throughout the source file that contains its declaration, but throughout all the files of the package.
- So, the lifetime of a package-level variable is the entire execution of the program
- Local variables
- Visible only within the declared block
- Created each time the declaration statement is executed and live on until they become unreachable.
- A compiler may choose to allocate local variables on the heap or on the stack.
About Pointers discussion
- Not every value has an address, but every variable does.
- The type of a pointer to
- The zero value for a pointer of any type is
- It is perfectly safe for a function to return the address of a local variable.
Can I use
++i, instead of
- No. In
++is a statement, not an expression.
- So, only
Many computations on constants can be completely evaluated at compile time, reducing the work necessary at run time and enabling other compiler optimizations.
Since their values are known to the compiler, * constant expressions may appear in types, specifically as the length of an array type*
You can use
iota to simplify
const declaration, which is replaced with incremental numbers from
Many constants are not committed to a particular type. The compiler represents these uncommitted constants with much greater numeric precision than values of basic types, and arithmetic on them is more precise than machine arithmetic; you may assume at least 256 bits of precision.