{"id":5025,"date":"2017-06-03T19:51:00","date_gmt":"2017-06-03T19:51:00","guid":{"rendered":"http:\/\/putridparrot.com\/blog\/?p=5025"},"modified":"2017-06-13T20:25:31","modified_gmt":"2017-06-13T20:25:31","slug":"starting-out-with-go","status":"publish","type":"post","link":"https:\/\/putridparrot.com\/blog\/starting-out-with-go\/","title":{"rendered":"Starting out with Go"},"content":{"rendered":"<p>I like learning different programming languages. Sometime I learn alternate ways to do things which might be useful in my usual language, sometimes I get a feel for how another language might be better for certain tasks and gives me more options for developing apps. I recently started learning the language Go, so this is my first of several posts on what I&#8217;ve learned.<\/p>\n<p><em>Note: I&#8217;m literally just learning this, so I suspect any posts on the subject will be pretty basic, but hopefully, might be of use to others (as well as myself).<\/em><\/p>\n<p><strong>Why Go?<\/strong><\/p>\n<p>Probably the first question many of us might ask is why pick a specific language. For example, is the language all about speed, or writing application in a specific paradigm like a functional language. <\/p>\n<p>So Why Go? Where does it fit into?<\/p>\n<p>Before we look to answer that question, we should note that <a href=\"https:\/\/en.wikipedia.org\/wiki\/Go_(programming_language)\" target=\"_blank\">Go was designed by Google<\/a> as an open source, compiled and statically typed language.<\/p>\n<p>So we might view Go as a possibly modern take on C but with features, such as concurrency as primitives as well as being a garbage collected language. It&#8217;s cross platform and compiles to native. The language is a general purpose language, so it can do many things, but I&#8217;ve not found anything to suggest it&#8217;s aimed at GUI work. I&#8217;ve seen lots of talk about supporting distributed code, and services\/microservices etc. but not yet done anything with these, so cannot confirm how good it is as such things.<\/p>\n<p><strong>Let&#8217;s get started and download Go<\/strong><\/p>\n<p>Okay, so you can read a brief history of Go from Wikipedia etc., let&#8217;s instead download Go and install it from <a href=\"https:\/\/golang.org\/dl\/\" target=\"_blank\">Downloads<\/a>.<\/p>\n<p>On Windows (as I&#8217;m currently running it) by default the installation is into C:\\Go and this is what the environment variable %GOROOT% should be set to (either during installation or manually assigned if need be). <\/p>\n<p>You&#8217;ll need to set up the %GOPATH% environment variable (or via your preferred IDE, I&#8217;m using JetBrains Gogland (1.0 Preview)) to point to your workspace, i.e. where you&#8217;ll be writing your application(s) to. So, for example, C:\\Development\\GoglandProjects on my installation is where I&#8217;m writing my Go projects to at the moment.<\/p>\n<p><em>Note: You do seem to be able to get away without a GOPATH.<\/em><\/p>\n<p><strong>Hello World<\/strong><\/p>\n<p>Yes, this one&#8217;s on <a href=\"https:\/\/golang.org\/\" target=\"_blank\">The Go Programming Language<\/a> website, but we&#8217;ll recreate here.<\/p>\n<ul>\n<li>In your workspace create a HelloWorld folder<\/li>\n<li>Create the file hello-world.go in your preferred editor<\/li>\n<li>Type into the file, the following\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\npackage main\r\n\r\nimport &quot;fmt&quot;\r\n\r\nfunc main() {\r\n   fmt.Println(&quot;Hello World&quot;)\r\n}\r\n<\/pre>\n<\/li>\n<li>From a command prompt (within the workspace\\HelloWorld folder) run\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">\r\ngo build hello-world.go\r\n<\/pre>\n<p>or even simpler (if you&#8217;re in the code&#8217;s folder), just run<\/p>\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">\r\ngo build\r\n<\/pre>\n<p>This command compiled the Go code into a native EXE\n<\/li>\n<\/ul>\n<p>At this point you&#8217;ll have a binary (hello-world.exe) that you can run or if you delete this and run the following line from the command prompt in your workspace<\/p>\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">\r\ngo run hello-world.go\r\n<\/pre>\n<p>then Go will compiled to a temporary EXE, i.e. no EXE is create in our workspace, it just runs the go code.<\/p>\n<p>In the hello-world.go code, you&#8217;ll see standard looking constructs, for example we have an include\/import\/using type line which imports the fmt package, you have a func main, which is obviously a function\/method (and should be in a package named main) and some call on the fmt package which ouputs to the console the string &#8220;Hello World&#8221;.<\/p>\n<p>So all pretty recognisable.<\/p>\n<p><em>Note: I mentioned fmt is a package and at first site this appears to be like an object\/class, but Go is not an object oriented language. There&#8217;s no inheritance for example, or base object but there are constructs that can give us some OO like capabilities, instead of objects we have structures &#8220;struct&#8221; types like in C as well as interfaces.<\/em><\/p>\n<p><strong>Basics<\/strong><\/p>\n<p>Here&#8217;s a quick list of some of the basics we expect to see in a language.<\/p>\n<p><em>Commenting<\/em><\/p>\n<p>The standard C++ \/\/ and \/* *\/ operators are used for single line and multi line comments respectively.<\/p>\n<p><em>Namespace\/Package<\/em><\/p>\n<p>Analogous to a namespace, we have the package &#8211; for example<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\npackage fmt\r\n<\/pre>\n<p><em>Creating your own types<\/em><\/p>\n<p>As mentioned, Go is not an OO language, but like C with typedef and struct we can create our own custom types, for example<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\ntype MyInteger int\r\n<\/pre>\n<p>or a struct using<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\ntype MyStructure struct {\r\n\ta MyInteger\r\n\tb MyInteger\r\n}\r\n<\/pre>\n<p><em>Declaring variables<\/em><\/p>\n<p>We define variables using the var keyword (like the optional usage in C#), i.e.<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\nvar myInteger = 3\r\n<\/pre>\n<p>In the case of situations where we want to declare the type. We declare the type after the variable name, i.e.<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\nvar myInteger MyInteger = 3\r\n<\/pre>\n<p>We could also use <\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\nvar myInteger = MyInteger(3)\r\n<\/pre>\n<p><stron\n\nTo declare a variable of a structure type me can use a similar syntax to C# and create like this\n\n[code language=\"c\"]\nvar myStructure = MyStructure{ a: 123, b: 876 }\n[\/code]\n\nAlternatively we can use the := syntax and remove the var and any type altogether, so for example\n\n[code language=\"c\"]\ns := MyStructure{ a: 123, b: 666}\n[\/code]\n\n<em>Note: Interestingly, declaring an unused variable results in a compile time error as does unused packages, this ensure you keep your code &#8220;clean&#8221; of anything not required.<\/em><\/p>\n<p><em>Basic types<\/em><\/p>\n<p>Ofcourse Go includes the basic types (see builtin.go) which include string, int, unit, byte, float, bool etc.<\/p>\n<p><em>Loops<\/em><\/p>\n<p>Ofcourse we for loops (see below), but interestingly no while loops<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\nfor i := 0; i &lt; 3; i++ {\r\n   fmt.Println(&quot;Hello&quot;)\r\n}\r\n<\/pre>\n<p>with the := reminds me of a Pascal crossed with C style. Notice no parenthesis are required around the for loop but braces are required.<\/p>\n<p>Also parenthesis must be placed (opening parenthesis {) on the same line as the loop (of if statements).<\/p>\n<p>Using a for loop like a while loop just means writing the following<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\ni := 0\r\nfor i &lt; 3 {\r\n   fmt.Println(&quot;Hello&quot;)\r\n   i++\r\n}\r\n<\/pre>\n<p>A while(true) infinite loop can be written as <\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\nfor {\r\n   fmt.Println(&quot;Hello&quot;)\r\n}\r\n<\/pre>\n<p><em>Flow control with if..else and switch statements<\/em><\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\nif i % 2 &gt; 0 {\r\n   fmt.Println(strconv.Itoa(i) + &quot; Odd&quot;)\r\n}\r\n<\/pre>\n<p>We can also declare\/assign variables as part of the if statement, for example<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\nif isOdd := i % 2; isOdd &gt; 0 {\r\n   fmt.Println(strconv.Itoa(i) + &quot; Odd&quot;)\r\n}\r\n<\/pre>\n<p>else statements must be on the closing brace line and their opening brace on the same line also, for example<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\nif isOdd := i % 2; isOdd &gt; 0 {\r\n   fmt.Println(strconv.Itoa(i) + &quot; Odd&quot;)\r\n} else {\r\n   fmt.Println(strconv.Itoa(i) + &quot; Even&quot;)\r\n}\r\n<\/pre>\n<p>Switch statements are pretty much as per C# etc.<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\nswitch i % 2 {\r\ncase 0:\r\n   fmt.Println(strconv.Itoa(i) + &quot; Odd&quot;)\r\ndefault:\r\n   fmt.Println(strconv.Itoa(i) + &quot; Even&quot;)\r\n}\r\n<\/pre>\n<p>like if statements, we can also assign variables and test them after the switch keyword and before the opening brace.<\/p>\n<p><em>Functions<\/em><\/p>\n<p>As mentioned already, we create functions using the func keyword. Functions can take arguments and return values (as you&#8217;d expect). For example<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\nfunc isOdd(i int) bool {\r\n\treturn i % 2 != 0\r\n}\r\n<\/pre>\n<p>Note: we declare the return type after the function (or no type for the equivalent of a void function) and we use the <em>return<\/em> keyword as per many C like languages.<\/p>\n<p>We can pass multiple arguments into a function in the standard way<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\nfunc doSomething(i int, test bool) bool {\r\n\/\/ do something\r\n}\r\n<\/pre>\n<p>we can also group arguments of the same type like so<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\nfunc doSomething(a, b, c int) bool {\r\n\/\/ do something\r\n}\r\n<\/pre>\n<p>We&#8217;ve shown code returning a single value, but we can also return tuples easily using the following syntax<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\nfunc doSomething() (string, string) {\r\n\treturn &quot;Hello&quot;, &quot;World&quot;\r\n}\r\n<\/pre>\n<p>and assigning this we would have something like<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\na, b := doSomething()\r\n<\/pre>\n<p>We can create anonymous functions using the func() syntax, for example<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\nfunc doSomething() func() string {\r\n\treturn func() string {\r\n\t\treturn &quot;Hello World&quot;\r\n\t}\r\n}\r\n<\/pre>\n<p>will return a function which returns a string.<\/p>\n<p>We can also pass variable arguments to a function (like vargs or params) using <\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\nfunc doSomething(args ...string) {\r\n\tfor _, arg := range args {\r\n\t\tfmt.Println(arg)\r\n\t}\r\n}\r\n<\/pre>\n<p>Note: in this example the _ is used as range returns a tuple of index (int) and the value (i.e. value[index]), The _ can be used in situations where we want to ignore a value and is special in that it will not cause an unused variable compile time error.<\/p>\n<p><em>Anonymous and named returns<\/em><\/p>\n<p>In the above we looked at declaring return values like this<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\nfunc doSomething() (string, string) {\r\n\treturn &quot;Hello&quot;, &quot;World&quot;\r\n}\r\n<\/pre>\n<p>in that the return (string, string) has no variable name associated with it, but we can also return named variables, for example<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\nfunc doSomething() (a string, b string) {\r\n\treturn &quot;Hello&quot;, &quot;World&quot;\r\n}\r\n<\/pre>\n<p>at this point the named returns only really demonstrate a use as a form of documentation, but they also get automatically initialized to the defaults for the type and can be used in a similar way to the out  keyword in C#, i.e. we can assign to them.<\/p>\n<p>Here&#8217;s an example<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\nfunc doSomething() (a string, b string) {\r\n\ta = &quot;Hello&quot;\r\n\tb = &quot;World&quot;\r\n\treturn\r\n}\r\n<\/pre>\n<p>so here we assign the named return a value and then we must still use a return. This allows us to build up the return tuple during the flow of the function, instead of storing as a local variable until we return the tuple.<\/p>\n<p><em>Arrays<\/em><\/p>\n<p>Let&#8217;s end this post with arrays. The standard [] syntax is used, here we declare an array and initialize it<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\na := &#x5B;2]string{&quot;Hello&quot;, &quot;World&quot;}\r\n<\/pre>\n<p>arrays are base 0 index, hence<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\nfmt.Println(a&#x5B;0]) \r\n<\/pre>\n<p>will result in Hello output to the console.<\/p>\n<p><em>Package visibility<\/em><\/p>\n<p>Functions and methods with a capitalized first letter (i.e. Pascal case) are public, whereas a lowercase first letter (i.e. Camel case) are private to the package. <\/p>\n<p>In other words the public functions are visible globally whereas private are visible only within the package.<\/p>\n<p><strong>References<\/strong><\/p>\n<p><a href=\"https:\/\/golang.org\/\" target=\"_blank\">The Go Programming Language<\/a><br \/>\n<a href=\"https:\/\/gobyexample.com\/\" target=\"_blank\">Go by example<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>I like learning different programming languages. Sometime I learn alternate ways to do things which might be useful in my usual language, sometimes I get a feel for how another language might be better for certain tasks and gives me more options for developing apps. I recently started learning the language Go, so this is [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[178],"tags":[],"class_list":["post-5025","post","type-post","status-publish","format-standard","hentry","category-go"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/5025","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/comments?post=5025"}],"version-history":[{"count":20,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/5025\/revisions"}],"predecessor-version":[{"id":5150,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/5025\/revisions\/5150"}],"wp:attachment":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/media?parent=5025"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/categories?post=5025"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/tags?post=5025"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}