Golang variables: Difference between revisions
From wikinotes
(28 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
= Assignment = | = Documentation = | ||
<blockquote> | |||
{| class="wikitable" | |||
|- | |||
| <code>new()</code> || https://go.dev/doc/effective_go#allocation_new | |||
|- | |||
| <code>make()</code> || https://go.dev/doc/effective_go#allocation_make | |||
|- | |||
|} | |||
</blockquote><!-- Documentation --> | |||
= Allocation = | |||
<blockquote> | |||
There are two keywords for allocating memory. | |||
<syntaxhighlight lang="go"> | |||
new(MyType) // allocate memory without initialization, return pointer (works for any type) | |||
make(MyType) // for slice/map/channel only, allocates/initializes, returns instance | |||
</syntaxhighlight> | |||
</blockquote><!-- Allocation --> | |||
= Process Variables = | |||
<blockquote> | |||
== Commandline Parameters == | |||
<blockquote> | |||
commandline arguments are stored in <code>os.Args</code> | |||
<syntaxhighlight lang="go"> | |||
for _, arg := range os.Args[1:] { | |||
switch arg { | |||
case "-h", "--help": | |||
// .. print help | |||
case "-v", "--verbose": | |||
// .. enable verbose logging | |||
} | |||
} | |||
</syntaxhighlight> | |||
</blockquote><!-- Call Parameters --> | |||
== Environment Variables == | |||
<blockquote> | |||
<syntaxhighlight lang="go"> | |||
import "os" | |||
path, err := os.LookupEnv("HOME") // "/home/will" | |||
err := os.SetEnv("FOO", "BAR") | |||
vars = os.Environ() // ["FOO=BAR", "BAR=BAZ", ...] | |||
</syntaxhighlight> | |||
</blockquote><!-- Environment Variables --> | |||
</blockquote><!-- Process Variables --> | |||
= Go Variables = | |||
<blockquote> | |||
== Assignment == | |||
<blockquote> | <blockquote> | ||
<syntaxhighlight lang="go"> | <syntaxhighlight lang="go"> | ||
Line 13: | Line 66: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- Assignment --> | </blockquote><!-- Assignment --> | ||
== Scope == | |||
<blockquote> | |||
<syntaxhighlight lang="go"> | |||
// global variables are defined outside of functions | |||
foo_global := "bar" | |||
// local variables defined in functions | |||
func main() { | |||
foo_local := "bar" | |||
} | |||
</syntaxhighlight> | |||
go supports closures (although to be async friendly, it is recommended to explicitly pass params) | |||
<syntaxhighlight lang="go"> | |||
func main() { | |||
a := 123 | |||
func() { | |||
fmt.Println("value of a:", a) | |||
} | |||
} | |||
</syntaxhighlight> | |||
Exported symbols (functions, variables) begin with a capital letter.<br> | |||
this means they can be used by files that import this package. | |||
<syntaxhighlight lang="go"> | |||
Foo := "bar" | |||
func MyPublicFunc() { ... } | |||
</syntaxhighlight> | |||
Exported symbols from packages defined within an <code>internal/</code> directory are only exported within your go module.<br> | |||
Consumers of your go module and it's packages will not have access to these symbols. | |||
</blockquote><!-- Scope --> | |||
== Type Conversion == | |||
<blockquote> | |||
general | |||
<syntaxhighlight lang="go"> | |||
float32(123) == 123. // cast int as float32 | |||
string(107) == "k" // retrieve char for 107 in ascii chart | |||
</syntaxhighlight> | |||
strings | |||
<syntaxhighlight lang="go"> | |||
strconv.Itoa(107) == "107" // represent 107 as string | |||
</syntaxhighlight> | |||
interfaces and concretions | |||
<syntaxhighlight lang="go"> | |||
// cast var typed as interface, | |||
// to it's concretion (so you can use it's methods) | |||
var foo MyInterface | |||
foo = MyConcretion{} | |||
castFoo := foo.(MyConcretion) | |||
// cast var typed as interface, | |||
// whose concretion has pointer methods | |||
// to it's concretion (so you can use it's methods) | |||
var foo MyInterface | |||
foo = MyConcretion{} | |||
castFoo := foo.(*MyConcretion) | |||
</syntaxhighlight> | |||
</blockquote><!-- Type Conversion --> | |||
== Introspection == | |||
<blockquote> | |||
<syntaxhighlight lang="go"> | |||
fmt.Prinf("%T\n", myVar) // print type of myVar | |||
</syntaxhighlight> | |||
</blockquote><!-- Introspection --> | |||
== Constants == | |||
<blockquote> | |||
=== Basics === | |||
<blockquote> | |||
<syntaxhighlight lang="go"> | |||
const myVar := "hi" // variable that cannot be reassigned | |||
const MyVar := "hi" // exported variable, that cannot be reassigned | |||
const myVar = 2 // infer constant type | |||
const ( // group constant assignment | |||
name string = "foo" | |||
age int = 123 | |||
) | |||
</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. | |||
* If inferring a constant, it's type may take on the type of an operation it is used with. (likely best to explicitly declare type) | |||
</blockquote><!-- Basics --> | |||
=== iota === | |||
<blockquote> | |||
See enums in [[golang datatypes]] | |||
</blockquote><!-- iota --> | |||
</blockquote><!-- Constants --> | |||
== Mutability == | |||
<blockquote> | |||
=== Mutable === | |||
<blockquote> | |||
<syntaxhighlight lang="yaml"> | |||
- Arrays | |||
- Maps | |||
- Channels | |||
- Structs | |||
</syntaxhighlight> | |||
</blockquote><!-- Mutable --> | |||
=== Immutable === | |||
<blockquote> | |||
<syntaxhighlight lang="yaml"> | |||
- Interfaces | |||
- Booleans | |||
- Numeric Types | |||
- Strings | |||
- Pointers | |||
</syntaxhighlight> | |||
</blockquote><!-- Immutable --> | |||
</blockquote><!-- Mutability --> | |||
</blockquote><!-- Go Variables --> |
Latest revision as of 20:31, 1 August 2022
Documentation
new()
https://go.dev/doc/effective_go#allocation_new make()
https://go.dev/doc/effective_go#allocation_make
Allocation
There are two keywords for allocating memory.
new(MyType) // allocate memory without initialization, return pointer (works for any type) make(MyType) // for slice/map/channel only, allocates/initializes, returns instance
Process Variables
Commandline Parameters
commandline arguments are stored in
os.Args
for _, arg := range os.Args[1:] { switch arg { case "-h", "--help": // .. print help case "-v", "--verbose": // .. enable verbose logging } }Environment Variables
import "os" path, err := os.LookupEnv("HOME") // "/home/will" err := os.SetEnv("FOO", "BAR") vars = os.Environ() // ["FOO=BAR", "BAR=BAZ", ...]
Go Variables
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"Scope
// global variables are defined outside of functions foo_global := "bar" // local variables defined in functions func main() { foo_local := "bar" }go supports closures (although to be async friendly, it is recommended to explicitly pass params)
func main() { a := 123 func() { fmt.Println("value of a:", a) } }Exported symbols (functions, variables) begin with a capital letter.
this means they can be used by files that import this package.Foo := "bar" func MyPublicFunc() { ... }Exported symbols from packages defined within an
internal/
directory are only exported within your go module.
Consumers of your go module and it's packages will not have access to these symbols.Type Conversion
general
float32(123) == 123. // cast int as float32 string(107) == "k" // retrieve char for 107 in ascii chartstrings
strconv.Itoa(107) == "107" // represent 107 as stringinterfaces and concretions
// cast var typed as interface, // to it's concretion (so you can use it's methods) var foo MyInterface foo = MyConcretion{} castFoo := foo.(MyConcretion) // cast var typed as interface, // whose concretion has pointer methods // to it's concretion (so you can use it's methods) var foo MyInterface foo = MyConcretion{} castFoo := foo.(*MyConcretion)Introspection
fmt.Prinf("%T\n", myVar) // print type of myVar
Constants
Basics
const myVar := "hi" // variable that cannot be reassigned const MyVar := "hi" // exported variable, that cannot be reassigned const myVar = 2 // infer constant type const ( // group constant assignment name string = "foo" age int = 123 )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.
- If inferring a constant, it's type may take on the type of an operation it is used with. (likely best to explicitly declare type)
iota
See enums in golang datatypes
Mutability
Mutable
- Arrays - Maps - Channels - StructsImmutable
- Interfaces - Booleans - Numeric Types - Strings - Pointers