将结构转换为golang中的结构 [英] convert struct to struct in golang

查看:182
本文介绍了将结构转换为golang中的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  type user1 struct {
姓氏字符串
姓氏字符串
用户名字符串
}

类型user2结构{
姓氏字符串
姓氏字符串
}


解决方案

最简单的方法是简单地执行 u2:= user2 {名字:u1.FirstName,LastName:u1.LastName} 。这是假设你不介意用户名在转换中丢失。



使用反射可以构建更通用的转换器,但我通常会尝试结构我的代码,所以它不需要。


trying to figure out what the best option is to convert one struct to another, Example

type user1 struct {
    FirstName string
    LastName string
    UserName string
}

type user2 struct {
    FirstName string
    LastName string
}

解决方案

The easiest is probably to simply do something like u2 := user2{FirstName: u1.FirstName, LastName: u1.LastName}. That is assuming you don't mind that the username is lost in the "conversion".

It's possible to build more general converters using reflection, but I would normally try to structure my code so it's not needed.

这篇关于将结构转换为golang中的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆