
The GO Language is a strongly typed language that means that in most cases it is impossible for an integer type variable to become a string type, as we can see in other languages. But, as in all highly typed languages there are certain operations that allow under certain conditions to _convert from one type to another. Careful we are talking here about conversion from one type to another and not to change the type of the variable.
We are talking about conversion or caster.
Here are examples of operations that range from errors to compilation in the GO language
This example will cause an error in the compilation, in addition, if you work for example under Visual Code, it will tell you with a red underscore, even before the compilation of this error.
.\main.go:11:37: cannot use ""Resultat: "" (type untyped string) as type int
package main import ( "fmt" ) func main() { var resultat int = 1 var monTexte string = "Resultat: " + resultat fmt.Printf("%v\n", monTexte) }
In JavaScript no worries, the result will be string type.
var result = 9; var myText = """Result: "" + result; document.write(myText);
This example will cause an error in the compilation, in addition, if you work for example under Visual Code, it will tell you with a red underscore, even before the compilation of this error. However, the error message is different:
.\main.go:11:29: constant 12.3 truncated to integer
package main import ( "fmt" ) func main() { var resultat int = 1 fmt.Printf("%v\n", resultat+12.3) }
You don’t need to convert sometimes, though. That’s why the GO Language and others allow it.
But in GO, you have to do it explicitly. An example will be more telling than a long speech.
package main import ( "fmt" ) func main() { var resultat float32 = 1.9 var resultatentier int = int(resultat) fmt.Printf("%v -> %v\n", resultat, resultatentier) }
1.9 -> 1
Attention: here we are talking about conversion, from one type to another. So in our example no rounding or particular action is undertaken by GO. It purely deletes the decimal part. So there will be a loss of information between the two.
Noted, however, that the GO language accepts certain operations between different types without problems and without specific details if and only if:
No loss of information or clarification is to be deplored.
CAUTION: only with values and not variables. For example, the following code will not compile as it requires an explicit conversion.
var resultat float32 = 1.9 var pv int = 100 s := resultat + pv <-- ERREUR A LA COMPILATION var resultat float32 = 1.9 var pv int = 100 s := resultat + float32(pv) <-- CONVERSION EXPLICITE
A CORRECT example.
package main import ( "fmt" ) func main() { var resultat float32 = 1.9 s := resultat + 100 // <-- int fmt.Printf("Sans Conversion : %v,%T\n", s, s) }
Sans Conversion : 101.9,float32
In summary
And now you know: