Home »
Golang »
Golang Find Output Programs
Golang const, Type Casting | Find Output Programs | Set 1
This section contains the Golang const, Type Casting find output programs (set 1) with their output and explanations.
Submitted by Nidhi, on August 13, 2021
Program 1:
package main
import "fmt"
func main() {
const num1 = 100
const num2 = 200
var sum = 0
sum = num1 + num2
fmt.Println("Sum: ", sum)
}
Output:
Sum: 300
Explanation:
In the above program, we created two constants num1 and num2 which was initialized with 100, 200 respectively. Then we added the values of num1 and num2 and assigned the result to the sum variable. After that, we printed the result on the console screen.
Program 2:
package main
import "fmt"
var num int=100;
const func Fun(){
num = 200;
}
func main() {
fmt.Println("Num: ",num);
Fun();
fmt.Println("Num: ",num);
}
Output:
./prog.go:7:7: syntax error: unexpected func, expecting name
./prog.go:7:12: const declaration cannot have type without expression
./prog.go:7:12: missing value in const declaration
Explanation:
The above program will generate syntax errors because we cannot create a const function in the Go language.
Program 3:
package main
import "fmt"
func main() {
const arr = [5]int{1, 2, 3, 4, 5}
for i := 0; i < 5; i++ {
fmt.Println(arr[i])
}
}
Output:
./prog.go:6:8: const initializer [5]int{...} is not a constant
Explanation:
The above program will generate a syntax error because we cannot create an array using the const keyword in the Go language.
Program 4:
package main
import "fmt"
type Student struct {
const id int=101;
age int ;
name string;
}
func main() {
stu := Student{name: "Amit", age: 28 }
fmt.Println(stu);
}
Output:
./prog.go:6:4: syntax error: unexpected const, expecting field name or embedded type
Explanation:
The above program will generate a syntax error because we cannot create the constant field of a structure.
Program 5:
package main
import "fmt"
func main() {
var num int = 100
const ptr *int = &num
fmt.Println(*ptr)
*ptr = 200
fmt.Println(num)
}
Output:
./prog.go:7:8: const initializer &num is not a constant
Explanation:
The above program will generate a syntax error because we cannot create a constant pointer like this in Go language.
Golang Find Output Programs »