Detect an anonymous struct using reflection

agolangf · · 604 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I&#39;m trying to extend an ODM and one of the methods will require me to return an error if an anonymous struct is passed. I can&#39;t just check against .Kind() using reflect.Struct since non-anonymous structs are handled a different way. </p> <p>Any ideas how I can do this without falling back to an awful string comparison against reflect.TypeOf(&lt;var&gt;).String()?</p> <p>Thanks.</p> <hr/>**评论:**<br/><br/>matttproud: <pre><p>I would expect that the package path for an anonymous struct would be empty or contain some other sentinel value:</p> <pre><code>t := reflect.TypeOf(struct{ field string }{}) fmt.Println(t.PkgPath() == &#34;&#34;) </code></pre> <p>… and it turns out this is the case: <a href="http://play.golang.org/p/GDHCkMXTzy" rel="nofollow">http://play.golang.org/p/GDHCkMXTzy</a>. However, this feels fragile to me, something liable to break in the future, because nothing in the specification speaks to this behavior.</p> <p>Further: this pattern works only if the type is <em>truly anonymous</em>. If you create <em>named type within the scope of a function</em>, it has both a name and a package path.</p></pre>JakeTheDev: <pre><p>I never thought about trying it this way. It still feels incredibly dirty, but less so than a string.Contains() against TypeOf().String().</p> <p>In my specific case, I only need to handle this if it <em>is</em> truly anonymous, so this concept will work for now. I wonder if the developers of Golang will improve the reflect package to allow an approach that ensures a bit more integrity.</p> <p>Thanks for your suggestion.</p></pre>klauspost: <pre><p>It is perfectly valid, and I would expect it to remain as such for Go 1.x. Anonumous structs will not suddenly be exported. However it will also be true if the passed struct type is just unexported.</p> <p>Here is some code that analyzes fields in a struct: <a href="http://play.golang.org/p/QjixAKL6_Q" rel="nofollow">http://play.golang.org/p/QjixAKL6_Q</a></p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

604 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传