How to Iterate the Fields of a Struct in Go

How to Iterate the Fields of a Struct in Go

To iterate the fields of a struct in Golang, you can use the reflect package’s ValueOf() function to iterate over the fields of a struct. package main import ( “fmt” “reflect” ) type Student struct { Name string Rollno int City string } func iterateStructFields(input interface{}) { value := reflect.ValueOf(input) numFields := value.NumField() fmt.Printf(“Number of … Read more

How to Get the Number of Characters in a String

How to Get the Number of Characters in a String

To get the number of characters in a string in Golang, you can use utf8.RuneCountInString() function from the unicode/utf8 package. This function correctly handles multi-byte characters (e.g., non-ASCII characters) encoded using UTF-8. Example package main import ( “fmt” “unicode/utf8” ) func main() { input := “Yello, 世界!” numOfRunes := utf8.RuneCountInString(input) fmt.Printf(“The number of characters in … Read more

How to Split a String on Whitespace in Go

How to Split a String on Whitespace in Go

To split a string on whitespace characters (spaces, tabs, and newlines) in Go, you can use the strings.Fields() function from the strings package.  package main import ( “fmt” “strings” ) func main() { input := “This is John Wick” words := strings.Fields(input) fmt.Println(“Words in the input string:”) for i, word := range words { fmt.Printf(“Word … Read more

How to Check If String Contains Substring in Golang

How to Check If String Contains Substring in Golang

To check if a string contains a substring in Golang, you can use the strings.Contains() function from the strings package. Example package main import ( “fmt” “strings” ) func main() { str := “Hello, Go is awesome!” substr := “Go” if strings.Contains(str, substr) { fmt.Printf(“String ‘%s’ contains the substring ‘%s’.\n”, str, substr) } else { … Read more

How to Check Nil in Golang

How to Check Nil in Golang

To check if a variable is a nil in Go, you can use the == comparison operator. The nil value is zero for pointers, functions, interfaces, maps, slices, and channels. When a variable of these types is not initialized, its value is nil. Example Here’s an example demonstrating how to check for nil values in Go. … Read more