Basic Golang (Go) Flashcards
Declare a variable of type string. (3 methods)
var myStringName string
var myStringName = “Hello there”
myStringName := “Hello there”
Declare a variable of type integer (3 methods)
var myIntegerName int
var myIntegerName = 5
myIntegerName := 5
Declare a variable of type float (3 methods)
var myFloatName float32
var myFloatName = 5.05
myFloatName := 5.05
Declare a variable of type boolean (3 methods)
var isThing bool
isThing bool = true
isThing := true
Declare a variable of type rune (3 methods)
var someRune rune
someRune rune = “🐻”
someRune := “🐻”
What is an anonymous function and when is it typically used?
In Go, an anonymous function, also known as a function literal, is a function defined without a name. It can be assigned to a variable, passed as an argument to another function, or executed directly. Anonymous functions are useful for short, one-time operations or when a function is needed only within a specific scope.
Using an example, assign a variable a value equal to an anonymous function where the value is “a” plus “b”
add := func(a, b int) int {
return a + b
}
result := add(5, 3)
A basic function named calcPrice that takes one integer (qty) and returns a float64.
func calcPrice(qty int) float64{
return qty * 0.99
}
A basic function named calcPrice that takes one integer (qty), two float64 (price and discount) and returns a float64 and boolean.
func calcPrice(qty int, price, discount float64) (float64, bool) {
cost := (qty * price) * (1 - discount)
isExpensive := false
return cost, isExpensive }
A basic struct named “car” with properties of brand, model, and mileage.
type car struct {
brand string
model string
mileage int
}