{"id":1244,"date":"2021-01-16T08:18:34","date_gmt":"2021-01-16T08:18:34","guid":{"rendered":"https:\/\/blog.samarthya.me\/wps\/?p=1244"},"modified":"2021-01-16T08:18:36","modified_gmt":"2021-01-16T08:18:36","slug":"golang-reflection","status":"publish","type":"post","link":"https:\/\/blog.samarthya.me\/wps\/2021\/01\/16\/golang-reflection\/","title":{"rendered":"GOLang: Reflection"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\">Must Read<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/blog.golang.org\/laws-of-reflection\">https:\/\/blog.golang.org\/laws-of-reflection<\/a><\/li><li><a href=\"https:\/\/golang.org\/pkg\/reflect\/\">https:\/\/golang.org\/pkg\/reflect\/<\/a><\/li><li><a href=\"https:\/\/golang.org\/pkg\/reflect\/#Kind\">https:\/\/golang.org\/pkg\/reflect\/#Kind<\/a><\/li><li><a href=\"https:\/\/golang.org\/pkg\/reflect\/#Value\">https:\/\/golang.org\/pkg\/reflect\/#Value<\/a><\/li><\/ul>\n\n\n\n<figure class=\"wp-block-pullquote is-style-solid-color\"><blockquote><p>Package reflect implements run-time reflection, allowing a program to manipulate objects with arbitrary types.<\/p><\/blockquote><\/figure>\n\n\n\n<p>Reflection is a way to examine own structure. Let&#8217;s try and learn it via examples.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func main() {\n\t\/\/exampleOne()\n\ti := 0\n\tfmt.Println(reflect.TypeOf(i))\n\tfmt.Println(reflect.ValueOf(i))\n}<\/code><\/pre>\n\n\n\n<p>Here I have defined a variable <code>i := 0<\/code> and inspecting it using reflection.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>int\n0<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-pullquote is-style-solid-color\"><blockquote><p>TypeOf returns the reflection Type that represents the dynamic type of i. <\/p><\/blockquote><\/figure>\n\n\n\n<pre class=\"wp-block-code\"><code>i := 0\nfmt.Println(\" Reflection: Int\")\nfmt.Println(reflect.TypeOf(i))\nfmt.Println(reflect.ValueOf(i))\nstr := \"Abc\"\nfmt.Println(reflect.TypeOf(str))\nfmt.Println(reflect.ValueOf(str))<\/code><\/pre>\n\n\n\n<p>The same way it works on other type<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>int\n0\nstring\nAbc<\/code><\/pre>\n\n\n\n<p>How about using a custom type instead of <code>int<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\ttype MyInt int\n\tvar myInt MyInt\n\t\n\tmyInt = 0\n\tfmt.Println(reflect.TypeOf(myInt))\n\tfmt.Println(reflect.ValueOf(myInt))<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>main.MyInt\n0<\/code><\/pre>\n\n\n\n<p>Variable <code>i<\/code> and <code>myInt<\/code> have distinct static types. Underlying types are same for both of them, but we cannot assign them to each other without conversion.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>myInt = i<\/code><\/pre>\n\n\n\n<p>Any statement like that will lead to a compile time error.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p>cannot use <code>i (type int)<\/code> as type <code>MyInt<\/code> in assignment<\/p><\/blockquote>\n\n\n\n<pre class=\"wp-block-code\"><code>i = 10\nmyInt = MyInt(i)\nfmt.Println(reflect.TypeOf(myInt))\nfmt.Println(reflect.ValueOf(myInt))<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>main.MyInt\n10<\/code><\/pre>\n\n\n\n<p>Let&#8217;s define a custom type with more content and read about using the <code>StructField<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ MyStructTags Reflect pacakge to learn more about a field.\ntype MyStructTags struct {\n\tFi int64   `json:\"intField\" defines:\"age\"`\n\tFb bool    `json:\"boolField\" defines:\"state\"`\n\tFf float64 `json:\"floatField\" defines:\"currency\"`\n\tFs string  `json:\"stringField\" defines:\"name\"`\n}\n\n\/\/ ReadTags Reads the tag\nfunc ReadTags(tt MyStructTags, ix int) {\n\tttType := reflect.TypeOf(tt)\n\tixField := ttType.Field(ix)                                                           \/\/ getting field at a position ix\n\tfmt.Printf(\"%v:%s:%v:%v\\n\", ixField.Tag, ixField.Name, ixField.Offset, ixField.Type) \/\/ printing tags\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>myRef := ref.MyStructTags{1, false, 1.52, \"What is my name?\"}\n\nfor i = 0; i &lt; 4; i++ {\n\tref.ReadTags(myRef, i)\n}<\/code><\/pre>\n\n\n\n<p>The output is as under<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>json:\"intField\" defines:\"age\":Fi:0:int64\njson:\"boolField\" defines:\"state\":Fb:8:bool\njson:\"floatField\" defines:\"currency\":Ff:16:float64\njson:\"stringField\" defines:\"name\":Fs:24:string<\/code><\/pre>\n\n\n\n<p>Looking at the documentation for the <code>SructField<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>type StructField struct {\n    \/\/ Name is the field name.\n    Name string\n    \/\/ PkgPath is the package path that qualifies a lower case (unexported)\n    \/\/ field name. It is empty for upper case (exported) field names.\n    \/\/ See https:\/\/golang.org\/ref\/spec#Uniqueness_of_identifiers\n    PkgPath string\n\n    Type      Type      \/\/ field type\n    Tag       StructTag \/\/ field tag string\n    Offset    uintptr   \/\/ offset within struct, in bytes\n    Index     &#91;]int     \/\/ index sequence for Type.FieldByIndex\n    Anonymous bool      \/\/ is an embedded field\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Setting Values<\/h2>\n\n\n\n<p>How about setting the value of the field?<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>type MyInt int\nvar myInt MyInt\n\nreflect.ValueOf(myInt).SetInt(22)<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-pullquote is-style-solid-color\"><blockquote><p>reflect: reflect.flag.mustBeAssignable using unaddressable value<\/p><\/blockquote><\/figure>\n\n\n\n<figure class=\"wp-block-pullquote is-style-solid-color\"><blockquote><p><em>Settability<\/em>\u00a0is a property of a reflection Value, and not all reflection Values have it.\u00a0<\/p><\/blockquote><\/figure>\n\n\n\n<pre class=\"wp-block-code\"><code>if reflect.ValueOf(myInt).CanSet() {\n\treflect.ValueOf(myInt).SetInt(22)\n}else {\n\tfmt.Println(\" CanSet returned false\")\n}<\/code><\/pre>\n\n\n\n<p>We will use <code>Elem<\/code> to set the value<\/p>\n\n\n\n<figure class=\"wp-block-pullquote is-style-solid-color\"><blockquote><p>Elem returns the value that the interface v contains or that the pointer v points to. It panics if v&#8217;s Kind is not Interface or Ptr. It returns the zero Value if v is nil.<\/p><\/blockquote><\/figure>\n\n\n\n<pre class=\"wp-block-code\"><code>fmt.Println(reflect.ValueOf(&amp;myInt).Kind())\nfmt.Println(reflect.ValueOf(&amp;myInt).Elem().CanSet())\nreflect.ValueOf(&amp;myInt).Elem().SetInt(24)\nfmt.Println(reflect.ValueOf(myInt).Interface())<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>ptr\ntrue\n24<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Must Read https:\/\/blog.golang.org\/laws-of-reflection https:\/\/golang.org\/pkg\/reflect\/ https:\/\/golang.org\/pkg\/reflect\/#Kind https:\/\/golang.org\/pkg\/reflect\/#Value Package reflect implements run-time reflection, allowing a program to manipulate objects with arbitrary types. Reflection is a way to examine own structure. Let&#8217;s try and learn it via examples. Here I have defined a variable i := 0 and inspecting it using reflection. TypeOf returns the reflection Type that [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":1253,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"image","meta":{"_exactmetrics_skip_tracking":false,"_exactmetrics_sitenote_active":false,"_exactmetrics_sitenote_note":"","_exactmetrics_sitenote_category":0,"footnotes":""},"categories":[137,34],"tags":[139,140],"class_list":["post-1244","post","type-post","status-publish","format-image","has-post-thumbnail","hentry","category-golang","category-technical","tag-go","tag-reflection","post_format-post-format-image"],"_links":{"self":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/posts\/1244","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/comments?post=1244"}],"version-history":[{"count":0,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/posts\/1244\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/media\/1253"}],"wp:attachment":[{"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/media?parent=1244"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/categories?post=1244"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.samarthya.me\/wps\/wp-json\/wp\/v2\/tags?post=1244"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}