What is the `Fields` function in Golang?
The Fields function in Golang splits a string into a list of substrings on the space character present in it.
The passed string is broken down into smaller substrings wherever one or more whitespace characters appear.
How to use the Fields function
To use this function, you must import the strings package in your file and access the Fields function within it using the . notation (string.Fields).
Here, Fields is the actual function, while string is the Go package that stores the function definition.
Function definition
The definition of the Fields function inside the string package is as follows:
Parameters
The Fields function takes a single argument:
str: This argument is of thestringtype and represents the text you want to split into whitespaces.
Return value
The Fields function returns a list (of the string type) of the substrings from the original string. The function does so by splitting the string on all instances of whitespaces.
Special return cases include:
-
When there are no whitespaces in the string, the whole string is returned as the only list member.
-
When a string contains only whitespaces, an empty list is returned.
Code
Example 1
In the example below, we split a sentence into whitespaces. We will use returned list’s elements to form another sentence.
package mainimport ("fmt""strings")func main() {x:= "Karim works at educative"y:= strings.Fields(x)fmt.Println(y[0], "is an employee at", y[3])}
Example 2
The following example shows the return value when you pass a string composed only of whitespaces to the Fields function.
package mainimport ("fmt""strings")func main() {x:= " "y:= strings.Fields(x)fmt.Println(y)}
Example 3
In this example, we observe what is returned when a string without any whitespaces is passed into the Fields function.
package mainimport ("fmt""strings")func main() {x:= "A_sentence_without_spaces"y:= strings.Fields(x)fmt.Println(y)}