Home »
Golang »
Golang Find Output Programs
Golang Goroutine, Map, and Reflection | Find Output Programs | Set 4
This section contains the Golang Goroutine, Map, and Reflection find output programs (set 4) with their output and explanations.
Submitted by Nidhi, on November 09, 2021
Program 1:
package main
import "fmt"
func main() {
CountryCode := make(map[string]int)
CountryCode["ind"] = 101
CountryCode["aus"] = 102
CountryCode["eng"] = 103
CountryCode["pak"] = 104
CountryCode["usa"] = 105
fmt.Println("Length of CountryCode: ", len(CountryCode))
}
Output:
Length of CountryCode: 5
Explanation:
In the above program, we created a map CountryCode to store codes of different countries. Then we printed the count of map elements.
Program 2:
package main
import "fmt"
func main() {
CountryCode := make(map[string]int)
CountryCode["ind"] = 101
CountryCode["aus"] = 102
CountryCode["eng"] = 103
CountryCode["pak"] = 104
CountryCode["usa"] = 105
fmt.Printf("\nMap elements: ")
for value := range CountryCode.values() {
fmt.Printf("\n%d", value)
}
}
Output:
./prog.go:15:32: CountryCode.values undefined (type map[string]int has no field or method values)
Explanation:
The above program will generate a syntax error because the values() method is not available in this context.
Program 3:
package main
import "fmt"
func main() {
CountryCode := make(map[string]int)
CountryCode["ind"] = 101
CountryCode["aus"] = 102
CountryCode["eng"] = 103
CountryCode["pak"] = 104
CountryCode["usa"] = 105
fmt.Printf("\nMap elements: ")
for Key, Value := range CountryCode {
fmt.Printf("\n%s : %d", Key, Value)
}
}
Output:
Map elements:
ind : 101
aus : 102
eng : 103
pak : 104
usa : 105
Explanation:
In the above program, we created a map CountryCode to store codes of different countries. Then we printed the keys and values of the created map using "range".
Program 4:
package main
import "fmt"
import "reflect"
func main() {
var num1 int = 10
var num2 byte = 20
var str string = "Hello"
fmt.Println("Type of num1 is: ", reflect.TypeOf(num1))
fmt.Println("Type of num2 is: ", reflect.TypeOf(num2))
fmt.Println("Type of str is : ", reflect.TypeOf(str))
}
Output:
Type of num1 is: int
Type of num2 is: uint8
Type of str is : string
Explanation:
In the above program, we created three different types of variables with some initial values. Then we printed the type of created variables using reflect.TypeOf() function and print the result.
Program 5:
package main
import "fmt"
import "reflect"
func main() {
fmt.Println("Type is: ", reflect.TypeOf(10))
fmt.Println("Type is: ", reflect.TypeOf("Hello"))
}
Output:
Type is: int
Type is: string
Explanation:
In the above program, we printed the type of specified values using reflect.TypeOf() function and print the result.
Golang Find Output Programs »