This section contains the Golang structures find output programs (set 2) with their output and explanations
Program 1:
package main
import "fmt"
type Sample struct {
Num1 int
Num2 int
Num3 int
}
func main() {
s1 := Sample{Num1: 100, Num2: 200, Num3: 300}
s2 := Sample{Num1: 400, Num2: 500, Num3: 600}
s3 := Sample{Num1: 700, Num2: 800, Num3: 900}
fmt.Println("Size of s1: ", Sizeof(s1))
fmt.Println("Size of s2: ", Sizeof(s2))
fmt.Println("Size of s3: ", Sizeof(s3))
}
Program 2:
package main
import "fmt"
import "unsafe"
type Sample struct {
Num1 int
Num2 int
Num3 int
}
func main() {
s1 := Sample{Num1: 100, Num3: 300}
s2 := Sample{Num3: 300, Num1: 100}
s3 := Sample{Num2: 200}
fmt.Println("Size of s1: ", unsafe.Sizeof(s1))
fmt.Println("Size of s2: ", unsafe.Sizeof(s2))
fmt.Println("Size of s3: ", unsafe.Sizeof(s3))
}
Program 3:
package main
import "fmt"
import "unsafe"
type Sample struct {
Num1 int
Num2 int
Num3 int
}
func main() {
var arr (2)Sample
arr[0].Num1 = 100
arr[0].Num2 = 200
arr[0].Num3 = 300
arr[1].Num1 = 100
arr[1].Num2 = 200
arr[1].Num3 = 300
fmt.Println("Size of arr[0]: ", unsafe.Sizeof(arr[0]))
fmt.Println("Size of arr[1]: ", unsafe.Sizeof(arr[1]))
}
Program 4:
package main
import "fmt"
// Declaration of structure
type Sample struct {
num1 int
Nested struct {
num2 int
}
}
func main() {
var obj Sample
obj.num1 = 10
obj.Nested.num2 = 20
fmt.Printf("Num1 : %d", obj.num1)
fmt.Printf("\nNum2 : %d", obj.Nested.num2)
}
Program 5:
package main
import "fmt"
func main() {
type MyType string
var str MyType = "Hello World"
fmt.Println("message: ", str)
}
Answer Program 1:
Output:
Explanation:
The above program will generate syntax errors because we used Sizeof(). Here we need to import unsafe package. The correct program is given below,
Answer Program 2:
Output:
Explanation:
In the above program, we created a structure Sample that contains Num1, Num2, Num3 members. Then we created the objects of the Sample structure and initialized them partially in the main() function.
After that, we printed the size of objects.
Answer Program 3:
Output:
Explanation:
The above program will generate a syntax error because we did on declared array properly. The correct declaration is given below,
var arr [2]Sample
Answer Program 4:
Output:
Explanation:
In the above we created a structure Sample, it contains a nested structure nested. In the main() function, we created object obj of structure Sample and initialized values. After that, we printed the result.
Answer Program 5:
Output:
Explanation:
In the above program, we created the alias name of the data-type string using the type keyword. Then we created a string variable str initialized with "Hello World". After that, we printed the str variable.