Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
String Formatting | Data Types
Introduction to GoLang
course content

Contenido del Curso

Introduction to GoLang

Introduction to GoLang

1. Getting Started
2. Data Types
3. Control Structures
4. Functions
5. Arrays and Slices
6. Intro to Structs & Maps

book
String Formatting

Now that we have learned about all the basic data types, we can explore string formatting. In programming, string formatting involves incorporating variable values into strings.

Note

The import statement is used to import packages into a Go application. A package is a collection of related Go source files that collaborate to offer a set of functionalities or services. The fmt package provides functions that allow us to format strings.

One of the functions from the fmt package that we have been using is the Println function. The Println function displays output text on a new line each time. However, there is a function called Print that displays output without moving to a new line:

go

index

copy
12345678
package main import "fmt" func main() { fmt.Print("1") fmt.Print(" 2") fmt.Print(" 3") }

In general, we can use these functions to insert variable values within string data using the following method:

go

index

copy
123456789
package main import "fmt" func main() { var n int = 5 var in int = n / 2 var out int = n - in fmt.Println("There are", n, "cats,", in, "of them are inside the house while", out, "are outside.") }

However, this method is not very efficient because we have to divide the string into many segments to insert variables at relevant places, which can become cumbersome in more complex cases. The Printf function addresses this issue and simplifies the process of displaying formatted output.

The Printf function takes a format string as its first argument, followed by values (or variables) to be inserted into the format string. A format string contains placeholders (format specifiers) that define the desired output's format.

Following is an example:

go

index

copy
12345678910
package main import "fmt" func main() { var n int = 5 var in int = n / 2 var out int = n - in fmt.Printf("There are %d cats, %d of them are inside the house with %d of them are outside. ", n, in, out) }

As illustrated by the example, Format Specifiers are symbols that serve as placeholders for specific data types within a string. There is a distinct format specifier for each data type. The table below provides a list of basic format specifiers:

Format SpecifierData Type
%dInteger
%sString
%fFloat
%tBoolean
%cCharacter (or Rune)

The variables substitute the respective placeholders in the format string. In the output of the example above, the first %d is replaced by the value of n. Similarly, the second is substituted with the corresponding variable, which is in, and the last %d is replaced by the value of out.

We can also format a string and store it inside a string variable using the Sprintf function, which formats a string and returns the resulting string for storage or use elsewhere, rather than immediately displaying it on the screen:

go

index

copy
123456789101112
package main import "fmt" func main() { var n int = 5 var in int = n / 2 var out int = n - in var text string = fmt.Sprintf("There are %d cats, %d of them are inside the house with %d of them are outside. ", n, in, out) fmt.Println("Text:", text) }

Here's a more complex example that incorporates multiple concepts we've previously covered in a single program. It will be a valuable exercise to review the following program and its output to enhance your code-reading skills:

go

index

copy
12345678910
package main import "fmt" func main() { var numA float32 = 17.7 var numB int = 10 var str string = fmt.Sprintf("It is %t that 'a' is bigger than 'b'.", numA > float32(numB)) fmt.Printf("The numbers 'a' and 'b' are %f and %d. %s", numA, numB, str) }

In some cases, the compiler performs implicit type casting to match values with format specifiers, as demonstrated in the following example:

go

index

copy
1234567
package main import "fmt" func main() { var char rune = 'A' fmt.Printf("The Unicode decimal value of %c is %d", char, char) }

The rune 'char' is outputted both as a character and as a numerical value. However, in some cases, the compiler might produce an error. For example, the following code will result in an invalid output because a 'float' cannot be implicitly converted into an 'int':

go

index

copy
12
var value float32 = 5.7 fmt.Printf("%d", value)
What will be the output of the program below?

What will be the output of the program below?

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 7
We're sorry to hear that something went wrong. What happened?
some-alt