我去过 reading about Golang 中的类型别名和组合结构。我希望能够拥有两个结构相同但可以在彼此之间轻松转换的结构。
我有一个父结构定义为:
type User struct {
Email string `json:"email"`
Password string `json:"password"`
}
一个组合结构定义为:
type PublicUser struct {
*User
}
我希望如果我定义一个 User:
a := User{
Email: "admin@example.net",
Password: "1234",
}
然后我可以执行以下类型转换:
b := (a).(PublicUser)
但它因无效的类型断言而失败:
invalid type assertion: a.(PublicUser) (non-interface type User on left)
如何在 Go 中结构相似的类型之间进行转换?
最佳答案
Go 中的类型断言让您可以使用接口(interface)的具体类型,而不是结构:
A type assertion provides access to an interface value's underlying concrete value.
https://tour.golang.org/methods/15
但是,稍加修改后,这段代码可以正常工作,并且可能会按照您的预期运行:
package main
import (
"fmt"
)
type User struct {
Email string `json:"email"`
Password string `json:"password"`
}
type PublicUser User
func main() {
a := User{
Email: "admin@example.net",
Password: "1234",
}
fmt.Printf("%#v\n", a)
// out: User{Email:"admin@example.net", Password:"1234"}
b := PublicUser(a)
fmt.Printf("%#v", b)
// out PublicUser{Email:"admin@example.net", Password:"1234"}
}
这里,PublicUser是对User类型的重新定义;最重要的是,它是一个独立的类型,共享字段,但不共享 User 的方法集(https://golang.org/ref/spec#Type_definitions)。
然后,您可以简单地使用 PublicUser 类型构造函数,就像您可能对 string/[]byte 转换所做的类似:foo := [ ]byte("foobar").
另一方面,如果您要使用实际的 type alias (type PublicUser = User) 您的输出将列出 User 作为两个实例的类型:PublicUser 只是旧事物的新名称,而不是新类型。
关于go - 在 Golang 中转换组合类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47964820/
我有一大串格式化数据(例如JSON),我想使用Psychinruby同时保留格式转储到YAML。基本上,我希望JSON使用literalstyle出现在YAML中:---json:|{"page":1,"results":["item","another"],"total_pages":0}但是,当我使用YAML.dump时,它不使用文字样式。我得到这样的东西:---json:!"{\n\"page\":1,\n\"results\":[\n\"item\",\"another\"\n],\n\"total_pages\":0\n}\n"我如何告诉Psych以想要的样式转储标量?解
我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串
我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)
有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳
我正在尝试解析一个CSV文件并使用SQL命令自动为其创建一个表。CSV中的第一行给出了列标题。但我需要推断每个列的类型。Ruby中是否有任何函数可以找到每个字段中内容的类型。例如,CSV行:"12012","Test","1233.22","12:21:22","10/10/2009"应该产生像这样的类型['integer','string','float','time','date']谢谢! 最佳答案 require'time'defto_something(str)if(num=Integer(str)rescueFloat(s
我正在玩HTML5视频并且在ERB中有以下片段:mp4视频从在我的开发环境中运行的服务器很好地流式传输到chrome。然而firefox显示带有海报图像的视频播放器,但带有一个大X。问题似乎是mongrel不确定ogv扩展的mime类型,并且只返回text/plain,如curl所示:$curl-Ihttp://0.0.0.0:3000/pr6.ogvHTTP/1.1200OKConnection:closeDate:Mon,19Apr201012:33:50GMTLast-Modified:Sun,18Apr201012:46:07GMTContent-Type:text/plain
我有一个小端顺序的字符串,作为十六进制编码的字符串000000020597ba1f0cd423b2a3abb0259a54ee5f783077a4ad45fb6200000218000000008348d1339e6797e2b15e9a3f2fb7da08768e99f02727e4227e02903e43a42b31511553101a051f3c00000000000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000我想将每个32位block从l
给定一个数组a,什么是实现其组合直到第n的最佳方法?例如:a=%i[abc]n=2#Expected=>[[],[:a],[:b],[:c],[:a,b],[:b,:c],[:c,:a]] 最佳答案 做如下:a=%w[abc]n=30.upto(n).flat_map{|i|a.combination(i).to_a}#=>[[],["a"],["b"],["c"],["a","b"],#["a","c"],["b","c"],["a","b","c"]] 关于ruby-最多n的组合,我
我正在研究csv生成。我正在分隔由逗号(,)分隔的值。如果字段中的值包含逗号,则不应在excel中分隔该字段。所以我想在那里放一个转义字符。我正在使用FasterCsv。那么我如何放置转义字符。fastercsv的转义字符是什么? 最佳答案 只需引用每个字段(默认为双引号),其中的逗号将被忽略:CSV.generate(:col_sep=>',',:quote_char=>'"')do|row|row"\"Quid,quid\",latinumdictum\n\"sit,altum\",viditur.\n"
我想合并多个事件记录关系例如,apple_companies=Company.where("namelike?","%apple%")banana_companies=Company.where("namelike?","%banana%")我想结合这两个关系。不是合并,合并是apple_companies.merge(banana_companies)=>Company.where("namelike?andnamelike?","%apple%","%banana%")我要Company.where("名字像?还是名字像?","%apple%","%banana%")之后,我会写代