
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Golang Program to Convert String to Object
In Golang program, a string is a data type that contains literals and characters whereas an object is a data type created from classes by keeping similar types of properties together. In this article, we will look at two methods by which we can convert a string to an object in go programming language.
Syntax
func Split(str, sep string) []string
Split() function is used to split a string through a provided separator. This function is present in strings package and it accepts the string to split as an argument along with a separator. The function then returns the final array of strings as a result.
func typeofobject(x interface{})
The typeof() function is used to get the type of any variable. This function is present in reflect package and it takes the variable whose type is to be determined as an argument. The function then returns the type of the variable specified as the result.
func Atoi(s string) (int, error)
Atoi() function is present in strings package and is used to convert a string to integer value. The function accepts the string value as an argument and returns the corresponding integer value after converting it. the function also returns an error variable that contains error if there is some problem in generating the output.
func ValueOf(i interface{}) Value
VslueOf() function is present in reflect package and is used to get the new Value initialized to the concrete value stored in the interface i. To access this function, one needs to imports the reflect package in the program.
Algorithm
Step 1 ? First, we need to import the fmt, json and reflect package.
Step 2 ? Then, create a structure named user and store Name and Age as properties to it.
Step 3 ? Then, create the main() function. Create a variable to string named input and store values to it.
Step 4 ? Next, create an empty variable named user as User type. Further, print the string variable on the screen.
Step 5 ? Now, call the Unmarshal() method present in json package and pass the input variable as byte array as argument to the function along with the user struct.
Step 6 ? No error will be shown if the conversion process is successful. Print the final result on the screen using fmt.Println().
Example 1: Using Json Package
In this program we will use json package to convert a string to an object.
package main import ( "encoding/json" "fmt" "reflect" ) type User struct { Name string Age int } func main() { input := `{"Name": "Alice", "Age": 25}` var user User fmt.Println("The given string is:", input, "and its type is:", reflect.TypeOf(input)) err := json.Unmarshal([]byte(input), &user) if err != nil { fmt.Println(err) return } fmt.Println() fmt.Printf("The object created from the above string is: %+v\n", user) }
Output
The given string is: {"Name": "Alice", "Age": 25} and its type is: string The object created from the above string is: {Name:Alice Age:25}
Example 2: Using Reflect Package
In this example we will write a go language program to convert a string to object using reflect package.
package main import ( "fmt" "reflect" "strconv" "strings" ) // creating user structure type User struct { Name string Age int } func main() { input := "Name:Alice Age:25" fmt.Println("The given string is:", input, "and its type is:", reflect.TypeOf(input)) values := strings.Split(input, " ") user := User{} // using for loop to iterate over the string for _, value := range values { parts := strings.Split(value, ":") if len(parts) != 2 { continue } key, val := parts[0], parts[1] v := reflect.ValueOf(&user).Elem() f := v.FieldByName(key) if !f.IsValid() { continue } if f.Type().Kind() == reflect.Int { age, err := strconv.Atoi(val) if err != nil { continue } f.SetInt(int64(age)) } else { f.SetString(val) } } fmt.Printf("The object obtained after converting string to object is: %+v\n", user) }
Output
The given string is: Name:Alice Age:25 and its type is: string The object obtained after converting string to object is: {Name:Alice Age:25}
Conclusion
We have successfully compiled and executed a go language program to convert a string to object along with examples. We have used two programs here in the first one we are using json package while in the second one we are using reflect package.