search
HomeCommon ProblemHow to convert struct in go language

How to convert struct in go language

Jun 16, 2023 pm 12:01 PM
gogo language

Go language conversion struct: 1. Convert struct to map, using the "TypeOf" and "ValueOf" functions in the reflect package to obtain the type and value of the struct, and then traverse each field of the struct. And store it into a map; 2. Convert map to struct. The input parameters are a map and a pointer to the struct. The output is empty. This function maps the values ​​in the map to the corresponding fields in the struct through reflection.

How to convert struct in go language

The operating environment of this tutorial: Windows 10 system, go1.20 version, Dell g3 computer.

Go language is a statically typed programming language. One of its characteristics is to define and organize complex data types through struct. Converting struct is one of the basic skills that must be mastered in Go language development. This article will introduce how to convert struct.

Definition of struct:

In Go language, you can define struct in the following way:

type Person struct {
Name string
Age int
}

This definition represents a Person type struct, It has two fields: Name and Age.

For a defined struct, we can instantiate an object and set its value in the following ways:

a := Person{
Name: "Alice",
Age: 20,
}

In this way, we can easily set variables of the struct type Assignment and use.

1. Convert struct to map

When we need to convert a struct type to a map type, we can use the following code:

func StructToMap(obj interface{}) map[string]interface{} {
objType := reflect.TypeOf(obj)
objVal := reflect.ValueOf(obj)
data := make(map[string]interface{})
for i := 0; i < objVal.NumField(); i++ {
data[objType.Field(i).Name] = objVal.Field(i).Interface()
}
return data
}

The The input parameter of the function is an interface type, and the output is a map type. This function uses the TypeOf and ValueOf functions in the reflect package to obtain the type and value of the struct. The function then iterates through each field of the struct and stores it into a map.

2. Convert map to struct

When we need to convert a map type to a struct type, we can use the following code:

func MapToStruct(m map[string]interface{}, s interface{}) {
sType := reflect.TypeOf(s).Elem()
sVal := reflect.ValueOf(s).Elem()
for i := 0; i < sType.NumField(); i++ {
field := sType.Field(i)
val := reflect.ValueOf(m[field.Name])
sVal.Field(i).Set(val)
}
}

The The input parameters of the function are a map and a pointer to a struct, and the output is empty. This function maps the values ​​in the map to the corresponding fields in the struct through reflection.

Summary:

Through the above introduction, we can see that in Go language, converting struct is very simple and can be easily achieved by using reflection. Through the above method, we can happily use the struct type and convert it during the development process of Go language, so as to develop more efficiently

The above is the detailed content of How to convert struct in go language. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Why does my lnk file have an arrow overlay?Why does my lnk file have an arrow overlay?Aug 26, 2025 am 05:04 AM

The guaronoona.lkfvisua.lkfvisuawingiShortiArtcut, noriotical ;notalfile; earthlpspreVUSIFUSECYSIGNLETHATELYTH eshortcutwonal'tdeleteal, Andhathef Resonance.1.TarroWabooth-LeftCorneroftToom

What to do when your Mac has a self-assigned IP address?What to do when your Mac has a self-assigned IP address?Aug 26, 2025 am 05:00 AM

IfyourMachasaself-assignedIPandnointernet,trythesesteps:1.RenewDHCPLeaseinNetworksettings.2.RestartrouterandMac.3.Removeandre-addWi-Fiservice.4.SetDNSto8.8.8.8and8.8.4.4.5.ResetnetworksettingsviaTerminalusingsudormcommand.

Why do I hear a beeping sound during my callWhy do I hear a beeping sound during my callAug 26, 2025 am 04:40 AM

Callwaitingalertscausebeepingwhensomeoneelsecallsduringanongoingcall;disablecallwaitinginphonesettingsifunwanted.2.Conferencecallsmayproducebeepswhenparticipantsjoinorleaveortoindicateactivestatus;thisisnormalforVoIPorgroupsystems.3.Lowbatteryonyourp

What are USB flash drives used for?What are USB flash drives used for?Aug 26, 2025 am 04:06 AM

USBflashdrivesaresmall,portablestoragedevicesthatconnecttocomputersandotherdevicesviaaUSBport.They’rewidelyusedforavarietyofeverydaytasksbecausethey’reconvenient,reliable,andcomeinlargestoragecapacitiesatlowcost.He

Can a virus change my 192.168.1.1 router settings?Can a virus change my 192.168.1.1 router settings?Aug 26, 2025 am 03:36 AM

Aviruscanchangeroutersettingsat192.168.1.1onlyifitaccessestheadmininterfaceusingknownorweakcredentials.2.Onceinside,malwarecanhijackDNS,disablefirewalls,changepasswords,orinstallbackdoors,asseenwiththreatslikeVPNFilter.3.Remoteadministrationincreases

What is the Lenovo Novo buttonWhat is the Lenovo Novo buttonAug 26, 2025 am 02:57 AM

IftheNovobuttonisn’tworking,ensurethedeviceispoweredoffandtrypressingthepinholebuttonwithapaperclip.Checkforproperbatterycharge,thenaccessthebootmenuorsystemrecoveryoptionsfromthebluescreen.

How to Add Text to a Non-Editable PDF?How to Add Text to a Non-Editable PDF?Aug 26, 2025 am 02:55 AM

Toaddtexttoanon-editablePDF,useaPDFeditorwithtextoverlaytools:1.OpenthePDFinsoftwarelikeAdobeAcrobatProDC.2.Usethe“EditPDF”toolandselect“AddText”(Aaicon).3.Clickanywhereonthepageandtypeyourtext.4.Adjustfont,size,andcolorusingthetoolbar.5.Savetheedite

Can't connect to WiFi after changing 192.168.1.1 settingsCan't connect to WiFi after changing 192.168.1.1 settingsAug 26, 2025 am 02:51 AM

Youlikelychangedtherouter’sIPorWi-Fisettingsincorrectly,causingaconnectionmismatch.Restarttherouteranddevice,thencheckthedefaultgatewayviaipconfigornetworksettingstofindthecurrentIP.2.IfWi-Fiwasmisconfigured,resettherouterbyholdingtheresetbuttonfor10

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Hot Topics