×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang const, Type Casting | Find Output Programs | Set 2

This section contains the Golang const, Type Casting find output programs (set 2) with their output and explanations.
Submitted by Nidhi, on August 13, 2021

Program 1:

package main

import "fmt"

func main() {
    var num1 float32=3.146;
    var num2 int=0;
    
    num2 = (int)num1;
    
    fmt.Println(num2);  
}

Output:

./prog.go:9:17: syntax error: unexpected num1 at end of statement

Explanation:

The above program will generate a syntax error because we cannot covert a floating-point number into an integer like this. The correct code is given below,

package main

import "fmt"

func main() {
	var num1 float32 = 3.146
	var num2 int = 0

	num2 = int(num1)

	fmt.Println(num2)
}

Program 2:

package main

import "fmt"

func main() {
	var num1 string = "123"
	var num2 int = 0

	num2 = int(num1)

	fmt.Println(num2)
}

Output:

./prog.go:9:12: cannot convert num1 (type string) to type int

Explanation:

The above program will generate a syntax error because we cannot covert numeric string into a number using the int() function. The correct code is given below,

package main

import "fmt"
import "strconv"

func main() {
	var num1 string = "123"
	var num2 int64 = 0

	num2, _ = strconv.ParseInt(num1, 0, 64)

	fmt.Println(num2)
}

Program 3:

package main

import "fmt"
import "strconv"

func main() {
	var num1 string = "123.456"
	var num2 float64 = 0

	num2, _ = strconv.ParseFloat(num1, 64)

	fmt.Println(num2)
}

Output:

123.456

Explanation:

In the above program, we converted a numeric string into a float point number using strconv.ParseFloat() function and print the result on the console screen.

Golang Find Output Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.