Demystifying Go (Golang), Google’s Programming Language: Basic Types - Conversions

Demystifying Go (Golang), Google’s Programming Language: Basic Types - Conversions

Introduction

Now that we’ve already explored how basic types work in Go and their respective zero-values (initial values), it’s time to learn a widely used concept in programming: conversion between basic types. Because, let’s be honest, at some point, you’ll want to turn that int into a string or that bool into something more useful—like a number. But Go has its peculiarities, and it’s always good to be prepared for them.

Bool

The bool type is straightforward: it’s either true or false, no drama there. But the interesting part comes when you want to convert it to other types. Let’s take a look at the most common ways to convert booleans to strings, and spoiler: there’s no native way to convert them directly to int (more on that later).

Sprint function: It’s part of the famous fmt package. It accepts multiple parameters of the any type and turns them into a single string. Although it’s not specific to bool, if you pass a single bool, it gets the job done.

Sprintf function: Also from the fmt package, but with a personalized touch. You can choose the specific output format (although for booleans, the options are limited to %v and %t).

FormatBool function: This one comes from the strconv package, specialized in conversions to and from strings. If you want to convert a boolean to a string without complication, this is your tool.

Check the example below to see how these functions work:

Now, if you’re wondering, “And converting bool to int?”, well, Go doesn’t give us that ease natively. But nothing that a custom function like boolToInt can’t solve.

Note: You can also convert bool to byte, but the code can get a bit complex. Let’s save that for a future post.

Byte

The byte type, which is essentially a uint8, can also be converted to string and int. The two most common conversions to string are:

  • Using the string type directly.
  • Using a conversion function.

And of course, conversion to int is the simplest: just use the int type itself. See an example below:

Attention: If you use direct conversion to string, Go won’t give you the number, but the corresponding character in the ASCII table. As shown in line 11 of the example above, where byte 97 is converted to the character 'a'. Surprise?

Int

Here the most popular conversions involve transforming int into string, float (when you need to perform calculations), and byte. Let’s look at the examples:

Just like byte, if you try to convert an int to string, it will be transformed into the corresponding character from the ASCII table. And yes, that can catch you off guard.

By the way, you might be wondering: "What does Itoa mean?" Well, this function converts an integer to a string, but instead of a direct name like IntToString, the Go team got creative and called it “Integer to alphanumeric”—hence the name Itoa.

Important: When you convert a large int32 to a smaller type like int16 or byte, Go won’t complain, but the results may be unexpected. See the magic (or confusion) below:

Float

Unlike other languages, Go splits floats into two types: float32 and float64. And here’s a trick: you can’t just assign a float32 to a float64 variable or vice versa. The compiler will yell at you if you try. You need an explicit conversion for that, as shown below:

When going the other way (converting float64 to float32), you also need to be explicit, but be careful with very large values that may result in +Inf—Go's equivalent of infinity.



When converting a float to int, Go doesn’t round the numbers. It simply removes everything after the decimal point, which might not be what you expected. Check it out:




String

To convert a string to the most common basic types, you’ll need the strconv package. Below are the most used functions:

  • ParseBool: Converts a string to a boolean.
  • ParseInt/Atoi: Converts a string to an integer.
  • ParseFloat: Converts a string to a float.

Let’s see how this works in practice:

If you want to ignore the error returned by the functions (because you’re sure the string is correct), you can use the underscore (_) to ignore the value, as in line 11 of the example.

For integers, we have ParseInt and its simpler sibling Atoi, which convert strings into numbers. Fun fact: Atoi is the inverse of Itoa, meaning “Alphanumeric to int.”


For floats, the process is the same. We use ParseFloat, which also returns an error if the conversion fails:

When the conversion fails, expect an error like the one below, in addition to receiving the zero value of the type you tried to convert:

Conclusion

Type conversion in Go is a learning journey, full of tricks and peculiarities. Go doesn’t make assumptions for you—it requires explicit conversions. And although that might seem like a hurdle at first, it ensures you always know exactly what’s going on in your code. Whether transforming a bool into a string or an int into a byte, the important thing is to understand the limits and expected behaviors to avoid surprises. So, next time you’re working with conversions in Go, remember these tips—they might save your day (and your code)!

Idalio Pessoa

Senior Ux Designer | Product Designer | UX/UI Designer | UI/UX Designer | Figma | Design System |

5 个月

Great job breaking down the complexities of type conversion in Go, Vagner Nascimento! I particularly appreciate how you highlighted the importance of explicit conversions to avoid surprises in the code. This attention to detail is crucial for creating seamless user experiences.

Elieudo Maia

Fullstack Software Engineer | Node.js | React.js | Javascript & Typescript | Go Developer

5 个月

Very informative

Gabriel Beretta

Senior Software Engineer | Fullstack Developer | Golang | Java | React | AWS

5 个月

Always great see more about Golang! ????

José Roberto

Software Engineer | Full-Stack Developer | ReactJS | NodeJS | AWS | Docker | Kubernetes | CI/CD | SQL | GIT

5 个月

Great advice, thanks for sharing, Vagner Nascimento

Fábio Salom?o

Software Engineer | Full Stack Developer | C# | .Net | React | Blazor | Typescript | Docker | Azure | Azure Devops | GitHub | API LLM

5 个月

Great article!! ??

要查看或添加评论,请登录

Vagner Nascimento的更多文章

社区洞察

其他会员也浏览了