在golang中,我想通过一个结构递归反射(reflect),得到字段的名称,它的类型和值。
这里的代码帮我反射(reflect)了golang recurisive reflection
问题是,当我尝试提取值时,当我在 ptr 值上反射(reflect)该值时,我总是感到 panic 。 是否可以反射(reflect)这两种类型,并继续传递值直到我到达原语,然后打印字段名称、类型和值?
这是我修改的代码:
func printType(prefix string, t reflect.Type, v reflect.Value visited map[reflect.Type]bool) {
// Print the name of this type with opening ( for description.
fmt.Printf("%s (", t)
// Traverse elements, adding to description as we go.
elems:
for {
switch t.Kind() {
case reflect.Ptr:
fmt.Print("ptr to ")
case reflect.Slice:
fmt.Print("slice of ")
case reflect.Array:
fmt.Printf("array with %d elements of ", t.Len())
default:
break elems
}
t = t.Elem()
}
// Print the kind of the type and the closing ) of the description.
// In the case of a struct, we print the names of the fields and recurse.
switch t.Kind() {
case reflect.Struct:
fmt.Printf("struct with %d fields)\n", t.NumField())
if visited[t] {
// Don't blow up on recursive type definition.
break
}
visited[t] = true
prefix += " "
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
// Get value for field
fieldValue := v.Field(i)
fmt.Print(prefix, f.Name, " ")
printType(prefix, f.Type, fieldValue, visited)
}
default:
fmt.Printf("%s) : %s\n", t.Kind(), v)
}
}
当我运行它时,我在调用 fieldValue := v.Field(i) 时感到 panic 关于如何实现这一点有什么想法吗?
谢谢
最佳答案
试试这个:
func printValue(prefix string, v reflect.Value, visited map[interface{}]bool) {
fmt.Printf("%s: ", v.Type())
// Drill down through pointers and interfaces to get a value we can print.
for v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface {
if v.Kind() == reflect.Ptr {
// Check for recursive data
if visited[v.Interface()] {
fmt.Println("visted")
return
}
visited[v.Interface()] = true
}
v = v.Elem()
}
switch v.Kind() {
case reflect.Slice, reflect.Array:
fmt.Printf("%d elements\n", v.Len())
for i := 0; i < v.Len(); i++ {
fmt.Printf("%s%d: ", prefix, i)
printValue(prefix+" ", v.Index(i), visited)
}
case reflect.Struct:
t := v.Type() // use type to get number and names of fields
fmt.Printf("%d fields\n", t.NumField())
for i := 0; i < t.NumField(); i++ {
fmt.Printf("%s%s: ", prefix, t.Field(i).Name)
printValue(prefix+" ", v.Field(i), visited)
}
case reflect.Invalid:
fmt.Printf("nil\n")
default:
fmt.Printf("%v\n", v.Interface())
}
}
因为可以从值中获取类型,所以不需要将类型传递给打印函数。
关于golang递归地反射(reflect)字段类型和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47664320/
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢
我可以得到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)
我知道我可以指定某些字段来使用pluck查询数据库。ids=Item.where('due_at但是我想知道,是否有一种方法可以指定我想避免从数据库查询的某些字段。某种反拔?posts=Post.where(published:true).do_not_lookup(:enormous_field) 最佳答案 Model#attribute_names应该返回列/属性数组。您可以排除其中一些并传递给pluck或select方法。像这样:posts=Post.where(published:true).select(Post.attr
有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过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
我几天前在我的rubyonrails2.3.2上安装了Sphinx和Thinking-Sphinx,基本搜索效果很好。这意味着,没有任何条件。现在,我想用一些条件过滤搜索。我有公告模型,索引如下所示:define_indexdoindexestitle,:as=>:title,:sortable=>trueindexesdescription,:as=>:description,:sortable=>trueend也许我错了,但我注意到只有当我将:sortable=>true语法添加到这些属性时,我才能将它们用作搜索条件。否则它找不到任何东西。现在,我还在使用acts_as_tag
假设您编写了一个类Sup,我决定将其扩展为SubSup。我不仅需要了解你发布的接口(interface),还需要了解你的私有(private)字段。见证这次失败:classSupdefinitialize@privateField="fromsup"enddefgetXreturn@privateFieldendendclassSub问题是,解决这个问题的正确方法是什么?看起来子类应该能够使用它想要的任何字段而不会弄乱父类(superclass)。编辑:equivalentexampleinJava返回"fromSup",这也是它应该产生的答案。 最佳答案