Golang variables: Difference between revisions
From wikinotes
Line 13: | Line 13: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- Assignment --> | </blockquote><!-- Assignment --> | ||
= Constants = | |||
<blockquote> | |||
<syntaxhighlight lang="go"> | |||
const myVar := "hi" // variable that cannot be reassigned | |||
const MyVar := "hi" // exported variable, that cannot be reassigned | |||
</syntaxhighlight> | |||
There are some rules for constant: | |||
* Constants cannot be assigned at runtime (ex. the result of a function). They must be static at compile time. | |||
* Constants must be assigned a immutable type (ex. collections are mutable, so they cannot be constants) | |||
* Inner scopes can declare the same constant with a new value. It will superseed the outer constant's value while working within that scope. | |||
</blockquote><!-- Constants --> | |||
= Type Conversion = | = Type Conversion = |
Revision as of 18:18, 29 May 2022
Assignment
// declare and assign variable var name string name = "foo" // declare and assign var in one step var name string = "foo" // declare and assign variable, inferring type name := "foo"
Constants
const myVar := "hi" // variable that cannot be reassigned const MyVar := "hi" // exported variable, that cannot be reassignedThere are some rules for constant:
- Constants cannot be assigned at runtime (ex. the result of a function). They must be static at compile time.
- Constants must be assigned a immutable type (ex. collections are mutable, so they cannot be constants)
- Inner scopes can declare the same constant with a new value. It will superseed the outer constant's value while working within that scope.
Type Conversion
float32(123) == 123. // cast int as float32 string(107) == "k" // retrieve char for 107 in ascii chart strconv.Itoa(107) == "107" // represent 107 as string
Introspection
fmt.Prinf("%T\n", myVar) // print type of myVar
Mutability
Mutable
- Arrays - Maps - Channels - StructsImmutable
- Interfaces - Booleans - Numeric Types - Strings - Pointers