Golang - Udemy Flashcards
Learning Golang
<p>Basic program</p>
package main
import “fmt”
func main(){ fmt.Println("Helllo World......") }
fmt.Println => accepts variadic parameters and returns multiple values
numBytes, err := fmt.Println(“hello’, 10, 20, “World”)
fmt.Println(a …args)(b, err)
Keywords
break default func interface select
case defer go map struct
chan else goto package switch
const fallthrough if range type
continue for import return var
Operators and Punctuations
+ & += &= && == != ( )
- | -= |= || < <= [ ]
* ^ *= ^= >= { }
/ «_space; /= «= ++ = := , ;
% »_space; %= »_space;= – ! … . :
&^ &^=
Variable Declaration
x := 10 => declares and assigns a variable
var x int => declares a variable and assign default
you cannot use := outside of function scope but you can use var
var x func foo(){ y := 20 }
x has package level scope
y has function level scope
Default values for Primitive datatypes
Boolean => false int => 0 float => 0.0 string => "" pointers => nil
Variable Types
var x := 10
fmr.Printf(“%T”, x) ==> int
var s := “hello world”
s = x => error since you are going to assign int to string
String Literals
s := hello world "how are you" ?
this will preserve the quotes and and carriage returns
Creating your own Type
var a int
type foo int
var b foo
a = 10 b = 20
a = b => error - unable to assign variable of one type to other
a = int(b) => works fine since we are Converting one type into another
Finding about computer architecture
runtime. GOOS - os (linux)
runtime. GOARCH - architectures - 32/64
String manipulations
s := “ABC”
for idx, v := range s{
fmt.Println(idx, v)
}
output == 0 A 1 B 2 C
Constants
const a = 10
const (
b = 20
c = 30
)
const k int = 200
Packages
two types
- executable
- reusable package
executable packages
- needs to have package main declaration at the start
- needs to have func main()
- produces an executable at the end of the build step.
reusable package can have any name and it does not produce an executable at the end of the build process.
Assigning value to a variable
var card string = “ace of spades”
card := “ace of spades”
both declarations are equivalent
:= is only used when you are creating a new variables and NOT when assigning values to an existing variable (you can use =)
Functions
func () {
}
Arrays
arrays - fixed size
slices - variable size
arr = [] string {"foo", "bar"} arr = append(arr, "baz")
append does not modify the existing array
it creates a new array and assigns values back to arr