<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by UH PLP on Medium]]></title>
        <description><![CDATA[Stories by UH PLP on Medium]]></description>
        <link>https://medium.com/@plp.project2019?source=rss-a16afe2a45c6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*uLFKWC7lJeFgu04L.jpg</url>
            <title>Stories by UH PLP on Medium</title>
            <link>https://medium.com/@plp.project2019?source=rss-a16afe2a45c6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 22:24:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@plp.project2019/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[10,900m Dive with Go]]></title>
            <link>https://medium.com/@plp.project2019/10-900m-dive-with-go-f236b35b8147?source=rss-a16afe2a45c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f236b35b8147</guid>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[UH PLP]]></dc:creator>
            <pubDate>Sun, 21 Apr 2019 22:36:10 GMT</pubDate>
            <atom:updated>2019-04-21T22:36:10.685Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Fun fact: The deepest manned vessel dive record is held by Jacques Picard and Don Walsh, at a depth of 10,911m (35,797ft). This record was set in 1960 when they reached the deepest point on the Earth, Challenger Deep.</blockquote><p>We close out our series on Golang with a look at Benchmark speeds, Safety, Memory Footprint, Ease of use and Reasons to use the language. You can find our last post <a href="https://medium.com/@plp.project2019/300m-dive-with-go-83b8c93268a5">here</a>.</p><h3>Benchmark Speeds</h3><p>We can reuse our functions and structure created in the post where we discussed Unit Testing. For convenience, I have linked it again. <a href="https://medium.com/@plp.project2019/200m-dive-with-go-91ea05921bdf">Click here</a>.</p><p>We can create a new file with the following code and add it to the calc_test package.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c148c9792fd2032ace2ea71989176be/href">https://medium.com/media/4c148c9792fd2032ace2ea71989176be/href</a></iframe><blockquote>Functions for benchmarking purposes are named BenchXXX with signature func (b *testing.B) according to standard naming convention.</blockquote><p>We can run this test using</p><p>go test -run=Bench -bench=.</p><blockquote>The -run flag takes in a regex that matches any function with our pattern.</blockquote><p>The output should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*6MPWX7KseePVOvCdGOmcsA.png" /></figure><p>We can provide more complex input to our benchmarks and see how it performs with each one.</p><h3>Safety</h3><p>When it comes to safety in programming language, there are two types of safety we will be interested in: type safety and memory safety.</p><p>Type safety is not a black-or-white type-safe or not. It’s more of a spectrum and some languages can be <em>more</em> type safe than others (and vice versa). Go is statically typed, but a number of features make it “appear” to be (at least somewhat) dynamically typed. For example, you do not need to explicitly mark your class as implementing any interfaces. If the method signatures of your class match up with those on the interface, then your class automatically implements that interface (a kind of duck-typing). This is useful for extending built-in classes and classes in third-party libraries, because you can just make up your interface to match the methods on the third-party class and it will automatically implement it.</p><p>Type safety is actually a different “axis” of the type system. Go is type-safe in the sense that you can’t mess around with types and crash the program (no direct access to pointers).</p><p>In terms of memory safety, Go is not memory safe in the presence of data races, and Go does not prevent data races at compile time.</p><p>On top of this Go does not enable ASLR on most OS’s. That means that when Go loads code from other languages, such as C/C++, memory safety issues in those languages are extremely easy to exploit relative to in a language like Rust, which enables tons of mitigation techniques by default.</p><h3>Memory Footprint</h3><p>Using the library runtime, we can determine how much memory is being used, how much has been used and how much the system has reserved.</p><p>The program below illustrates how much memory is allocated to objects on the heap using the Alloc variable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/033e11a3b0bb15b102bde82675c32a1a/href">https://medium.com/media/033e11a3b0bb15b102bde82675c32a1a/href</a></iframe><blockquote>Program referenced from <a href="https://golangcode.com/print-the-current-memory-usage/">here</a>.</blockquote><p>Run the program using go run mem_usage.go</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*GKjyHjNFWtNypWPtqLv6uQ.png" /></figure><p>Here we see that the allocated memory is not freed up unless the garbage collector is run.</p><h3>Ease of Use</h3><p>Programmers who could were choosing ease over safety and efficiency by moving to dynamically typed languages such as Python and JavaScript rather than C++ or, to a lesser extent, Java.</p><p>Go is an attempt to combine the ease of programming of an interpreted, dynamically typed language with the efficiency and safety of a statically typed, compiled language. It also aims to be modern, with support for networked and multicore computing.</p><p>While Go might not be as popular as JavaScript or Python, it does have one important thing in common with them: it’s eminently easy to understand. The syntax is clean and accessible to newcomers, and there aren’t a lot of complex functions to learn. But that slick and clean syntax offers advantages to more than just newbies. That’s because it’s an easy language to read as well, and that makes it a great choice for legacy code that may involve multiple coders iterating over each other’s code blocks. The close similarities to C-style languages mean that it will be a simple language to learn for programmers proficient in C++ or C#.</p><h3>Reasons to Use Go</h3><p>Whenever trying to pick a programming language to use, you may first begin by asking yourself what is the purpose for you to learn a new language. Once you determine that, you can begin looking at your options and determine, among other things, which would be the easiest to learn and the most efficient for what you’re tying to do.</p><p>That said, Go offers many features that could would make it an ideal programming language to use.</p><p>The main reason to choose Go over any other programming language is if your application requires concurrency, which Go is able to handle efficiently. This is due to Go treating concurrency as a first-class citizen through its goroutines. What are goroutines, you may ask. Well, goroutines are just functions that can be run concurrently with other functions, and can also be thought of as lightweight threads that are managed by the Go runtime. Furthermore, the cost of creating a thread in Java for example can be expensive whereas in Go , the cost of creating goroutines is minimal.</p><p>Go can be thought of as a general purpose programming language that can be seen as alternative to C, C++, or Java. Go is very easy to learn, and even easier if you are already familiar with another language with C-style syntax. Being a statically typed language, go supports type safety where errors are caught by the compiler before execution. One other reason to use Go, is because it also comes with efficient and concurrent automatic memory management to take away the overhead of managing the memory allocation.</p><p>Some examples of what Go can be sued for are:</p><ul><li>Restful servers</li><li>Backends</li><li>Microservices</li></ul><h4>Authors</h4><p>Zhuo Ai, Raul Rios, Joel Thomas</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f236b35b8147" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[300m Dive with Go]]></title>
            <link>https://medium.com/@plp.project2019/300m-dive-with-go-83b8c93268a5?source=rss-a16afe2a45c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/83b8c93268a5</guid>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[UH PLP]]></dc:creator>
            <pubDate>Mon, 01 Apr 2019 03:59:47 GMT</pubDate>
            <atom:updated>2019-04-01T03:59:47.090Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*ERojGMB35dNDZJtgdC-iFw.png" /></figure><blockquote>Fun fact: The deepest scuba dive record is held by an Egyptian named Ahmed Gabr, at a depth of 332.35m (1090.4ft)</blockquote><p>Continuing with our theme of deep dives, we cover Toolchains, Internals and Intermediate representation in Go in this post. You can read our last post <a href="https://medium.com/@plp.project2019/200m-dive-with-go-91ea05921bdf">here</a>.</p><h3>Toolchain</h3><p>A toolchain is a set of distinct software development tools that are linked (or chained) together by specific stages such as go. Optionally, a toolchain may contain other tools such as a debugger or a compiler for a specific programming language. Quite often, the toolchain used for embedded development is a cross toolchain, or more commonly known as a cross compiler. All the programs (like GCC) run on a host system of a specific architecture (such as x86), but they produce binary code (executables) to run on a different architecture (for example, ARM).</p><blockquote>From the docs: Go is a tool for managing Go source code.</blockquote><p>We’ve seen many uses of go in lieu with other commands to build or run our program.</p><p>Typically used:</p><p>go &lt;command&gt; [arguments]</p><p>Some of the commands are:</p><pre>build       compile packages and dependencies</pre><pre>clean       remove object files and cached files</pre><pre>doc         show documentation for package or symbol</pre><pre>env         print Go environment information</pre><pre>fmt         gofmt (reformat) package sources</pre><pre>install     compile and install packages and dependencies</pre><pre>list        list packages or modules</pre><pre>run         compile and run Go program</pre><pre>test        test packagesclean remove object files and cached files</pre><p><em>For a full list of commands, click </em><a href="https://golang.org/cmd/go/"><em>here</em></a><em>.</em></p><p><strong>Compile packages and dependencies</strong></p><p>Usage:</p><p>go build [-o output] [-i] [build flags] [packages]</p><p>Build compiles the packages named by the import paths, along with their dependencies, but it does not install the results. When compiling packages, build ignores files that end in ‘_test.go’.</p><p>The -i flag installs the packages that are dependencies of the target. The build flags are shared by the build, clean, get, install, list, run, and test commands:</p><pre>-a force rebuilding of packages that are already up-to-date.</pre><pre>-n print the commands but do not run them.</pre><pre>-v print the names of packages as they are compiled.</pre><p><em>For a full list of flags, click </em><a href="https://golang.org/cmd/go/#hdr-Compile_packages_and_dependencies"><em>here</em></a><em>.</em></p><p><strong>Remove object files and cached files</strong></p><p>Usage:</p><p>go clean [clean flags] [build flags] [packages]</p><p>The go command builds most objects in a temporary directory, so go clean is mainly concerned with object files left by other tools or by manual invocations of go build. Some of the files it removes are:</p><pre>_obj/            old object directory, left from Makefiles</pre><pre>_test/           old test directory, left from Makefiles</pre><pre>_testmain.go     old gotest file, left from Makefiles</pre><p><strong>Show documentation for package or symbol</strong></p><p>Usage:</p><p>go doc [-u] [-c] [package|[package.]symbol[.methodOrField]]</p><p>Doc prints the documentation comments associated with the item identified by its arguments (a package, const, func, type, var, method, or struct field) followed by a one-line summary of each of the first-level items “under” that item (package-level declarations for a package, methods for a type, etc.).</p><p>Examples:</p><pre>go doc Show documentation for current package.</pre><pre>go doc Foo Show documentation for Foo in the current package.(Foo starts with a capital letter so it cannot match a package path.)</pre><p><strong>Print Go environment information</strong></p><p>Usage:</p><p>go env [-json] [var …]</p><p>Env prints Go environment information. Some of the environment variables it prints are:</p><p>$GOOS and $GOARCH</p><p>The name of the target operating system and compilation architecture. These default to the values of $GOHOSTOS and $GOHOSTARCH respectively (described below).</p><p>$GOPATH</p><p>lists places to look for Go code</p><p>$GOROOT</p><p>The Go binary distributions assume they will be installed in /usr/local/go (or c:\Go under Windows)</p><p><strong>Compile and run Go program</strong></p><p>Usage:</p><p>go run [build flags] [-exec xprog] package [arguments…]</p><p>Run compiles and runs the named main Go package. Typically the package is specified as a list of .go source files, but it may also be an import path, file system path, or pattern matching a single known package, as in ‘go run .’ or ‘go run my/cmd’.</p><p><strong>Test packages</strong></p><p>Usage:</p><p>go test [build/test flags] [packages] [build/test flags &amp; test binary flags]</p><p>‘Go test’ automates testing the packages named by the import paths. It prints a summary of the test results in the format:</p><pre>ok   archive/tar   0.011s</pre><pre>FAIL archive/zip   0.022s</pre><pre>ok   compress/gzip 0.033s</pre><pre>...</pre><p>followed by detailed output for each failed package.</p><p>‘Go test’ recompiles each package along with any files with names matching the file pattern “*_test.go”. These additional files can contain test functions, benchmark functions, and example functions. Each listed package causes the execution of a separate test binary. Files whose names begin with “_” (including “_test.go”) or “.” are ignored.</p><h4>Cross Compiling</h4><p>Cross compilation is one of Go’s headline features. Cross compilers got easier since Go 1.5. You don’t have to bootstrap the standard library and toolchain as you used to do prior to 1.5.</p><p><strong>If cgo is not required</strong></p><blockquote>But first, what is cgo? Cgo enables the creation of Go packages that call C code. To use cgo write normal Go code that imports a pseudo-package “C”. The Go code can then refer to types such as C.size_t, variables such as C.stdout, or functions such as C.putchar.</blockquote><p>The go tool won’t require any bootstrapping if cgo is not required. That allows you to target the following program to any GOOS/GOARCH without requiring you to do any additional work. Invoke go build.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46639b2b534534c8e6a80412f15ba727/href">https://medium.com/media/46639b2b534534c8e6a80412f15ba727/href</a></iframe><p>In order to target android/arm, run the following command:</p><p>$ GOOS=android GOARCH=arm GOARM=7 go build .</p><p><strong>If cgo is required</strong></p><p>If you need to have cgo enabled, the go tool allows you to provide custom C and C++ compilers via CC and CXX environment variables.</p><p>$ CGO_ENABLED=1 CC=android-armeabi-gcc CXX=android-armeabi-g++ \GOOS=android GOARCH=arm GOARM=7 go build .</p><p>The toolchain will invoke android-armeabi-gcc and android-armeabi-g++ if it is required to compile any part of the package with a C or C++ compiler.</p><p>All possible $GOOS and $GOARCH values are listed on the <a href="https://golang.org/doc/install/source#environment">environment docs</a>.</p><h3><strong>Internals — Project Structure &amp; Compiler</strong></h3><h4>Understanding project structure</h4><p>If you look at the <em>/src</em> folder of the Go repository, you can see a lot of folders. Most of them contain source files of the standard Go library. The standard naming conventions are always applied here, so each package is inside a folder with a name that directly corresponds to the package name. Apart from the standard library, there is a lot of other stuff. In my opinion, the most important and useful folders are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*sgn2K8WVRQcZMTP1YD_2hw.png" /></figure><h4>Inside the Go compiler</h4><p>As I said above, the architecture-independent part of the Go compiler is located in the <a href="https://github.com/golang/go/tree/release-branch.go1.4/src/cmd/gc"><em>/src/cmd/gc/</em></a> folder. The entry point is located in the <a href="https://github.com/golang/go/blob/release-branch.go1.4/src/cmd/gc/lex.c#L199"><em>lex.c</em></a><em> </em>file. Apart from some common stuff, such as parsing command line arguments, the compiler does the following:</p><ol><li>Initializes some common data structures.</li><li>Iterates through all of the provided Go files and calls the yyparse method for each file. This causes actual parsing to occur. The Go compiler uses <a href="http://www.gnu.org/software/bison/">Bison</a> as the parser generator. The grammar for the language is fully described in the <a href="https://github.com/golang/go/blob/release-branch.go1.4/src/cmd/gc/go.y">go.y</a> file. As a result, this step generates a complete parse tree where each node represents an element of the compiled program.</li><li>Recursively iterates through the generated tree several times and applies some modifications, e.g., defines type information for the nodes that should be implicitly typed, rewrites some language elements—such as typecasting—into calls to some functions in the runtime package and does some other work.</li><li>Performs the actual compilation after the parse tree is complete. Nodes are translated into assembler code.</li><li>Creates the object file that contains generated assembly code with some additional data structures, such as the symbols table, which is generated and written to the disk.</li></ol><h3>Internals — The Object Files, Relocations, and Linker</h3><p>In Go, the high-level modules are the compiler, linker, and runtime. The interface that the compiler provides (and the linker consumes) is an object file.</p><h4>Generating a Go object file</h4><p>Let’s do an experiment: write a very basic program, compile it, and see what object file will be produced. In my case, the program was as follows:</p><pre>package main</pre><pre>func main() {<br>	print(1)<br>}</pre><p>Now we need to compile it:</p><pre>go tool 6g test.go</pre><p>This command produces the <em>test.6</em> object file. To investigate its internal structure, we are going to use the <a href="https://github.com/golang/go/tree/master/src/cmd/internal/goobj">goobj</a> library. It is employed internally in Go source code, mainly for implementing a set of unit tests that verifies whether object files are generated correctly in different situations. For this blog post, I wrote a very simple program that prints the output generated from the <em>googj</em> library to the console. You can take a look at the sources of this program <a href="https://github.com/s-matyukevich/goobj_explorer">here</a>.</p><p>First of all, you need to download and install my program:</p><pre>go get github.com/s-matyukevich/goobj_explorer</pre><p>Then, execute the following command:</p><pre>goobj_explorer -o test.6</pre><p>Now you should be able to see the <em>goob.Package</em> structure in your console.</p><h4>Investigating the object file</h4><p>The most interesting part of our object file is the <em>Syms</em> array. This is actually a symbol table. Everything that you define in your program — functions, global variables, types, constants, etc. — is written to this table. Let’s look at the entry that corresponds to the <em>main</em> function. (Note that I have cut the <em>Reloc</em> and <em>Func</em> fields from the output for now. We will discuss them later.)</p><pre>&amp;goobj.Sym{<br>            SymID: goobj.SymID{Name:&quot;main.main&quot;, Version:0},<br>            Kind:  1,<br>            DupOK: false,<br>            Size:  48,<br>            Type:  goobj.SymID{},<br>            Data:  goobj.Data{Offset:137, Size:44},<br>            Reloc: ...,<br>            Func:  ...,<br>}</pre><p>The names of the fields in the <em>goobj.Sum</em> structure are pretty self-explanatory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*H4n1_ShA6qnXo9VYP9aInw.png" /></figure><p>Now, let’s look at different kinds of symbols. All possible kinds of symbols are defined as constants in the <em>goobj</em> package (you can find them <a href="https://github.com/golang/go/blob/master/src/cmd/internal/goobj/read.go#L30">here</a>). Below, I copied the first part of these constants:</p><pre>const (<br>	_ SymKind = iota</pre><pre>	// readonly, executable<br>	STEXT<br>	SELFRXSECT</pre><pre>	// readonly, non-executable<br>	STYPE<br>	SSTRING<br>	SGOSTRING<br>	SGOFUNC<br>	SRODATA<br>	SFUNCTAB<br>	STYPELINK<br>	SSYMTAB // TODO: move to unmapped section<br>	SPCLNTAB<br>	SELFROSECT<br>	...</pre><p>As we can see, the <em>main.main</em> symbol belongs to kind 1 that corresponds to the <em>STEXT</em> constant. <em>STEXT</em> is a symbol that contains executable code. Now, let’s look at the <em>Reloc</em> array. It consists of the following structs:</p><pre>type Reloc struct {<br>	Offset int<br>	Size   int<br>	Sym    SymID<br>	Add    int<br>	Type int<br>}</pre><p>Each relocation implies that the bytes situated at the <em>[Offset, Offset+Size]</em> interval should be replaced with a specified address. This address is calculated by summing up the location of the <em>Sym</em> symbol with the <em>Add</em> number of bytes.</p><h4>Understanding relocations</h4><p>Now let’s use an example and see how relocations work. To do this, we need to compile our program using the <em>-S</em> switch that will print the generated assembly code:</p><pre>go tool 6g -S test.go</pre><p>Let’s look through the assembler and try to find the main function.</p><pre>&quot;&quot;.main t=1 size=48 value=0 args=0x0 locals=0x8<br>	0x0000 00000 (test.go:3)	TEXT	&quot;&quot;.main+0(SB),$8-0<br>	0x0000 00000 (test.go:3)	MOVQ	(TLS),CX<br>	0x0009 00009 (test.go:3)	CMPQ	SP,16(CX)<br>	0x000d 00013 (test.go:3)	JHI	,22<br>	0x000f 00015 (test.go:3)	CALL	,runtime.morestack_noctxt(SB)<br>	0x0014 00020 (test.go:3)	JMP	,0<br>	0x0016 00022 (test.go:3)	SUBQ	$8,SP<br>	0x001a 00026 (test.go:3)	FUNCDATA	$0,gclocals·3280bececceccd33cb74587feedb1f9f+0(SB)<br>	0x001a 00026 (test.go:3)	FUNCDATA	$1,gclocals·3280bececceccd33cb74587feedb1f9f+0(SB)<br>	0x001a 00026 (test.go:4)	MOVQ	$1,(SP)<br>	0x0022 00034 (test.go:4)	PCDATA	$0,$0<br>	0x0022 00034 (test.go:4)	CALL	,runtime.printint(SB)<br>	0x0027 00039 (test.go:5)	ADDQ	$8,SP<br>	0x002b 00043 (test.go:5)	RET	,</pre><p>Now, we are interested in the following line:</p><pre>0x0022 00034 (test.go:4)	CALL	,runtime.printint(SB)</pre><p>This command is located at an offset of 0x0022 (in hex) or 00034 (decimal) within the function data. This line is actually responsible for calling the <em>runtime.printint</em> function. The issue is that the compiler does not know the exact address of the <em>runtime.printint</em> function during compilation. This function is located in a different object file the compiler knows nothing about. In such cases, it uses relocations. Below is the exact relocation that corresponds to this method call (I copied it from the first output of the <em>goobj_explorer</em> utility):</p><pre>{<br>                    Offset: 35,<br>                    Size:   4,<br>                    Sym:    goobj.SymID{Name:&quot;runtime.printint&quot;, Version:0},<br>                    Add:    0,<br>                    Type:   3,<br>                },</pre><p>This relocation tells the linker that, starting from an offset of 35 bytes, it needs to replace 4 bytes of data with the address of the starting point of the <em>runtime.printint</em> symbol. But an offset of 35 bytes from the main function data is actually an argument of the call instruction that we have previously seen. (The instruction starts from an offset of 34 bytes. One byte corresponds to call instruction code and four bytes — to the address of this instruction.)</p><h4>How the linker operates</h4><p>Now that we understand this, we can figure out how the linker works. The following schema is very simplified, but it reflects the main idea:</p><ul><li>The linker gathers all the symbols from all the packages that are referenced from the main package and loads them into one big byte array (or a binary image).</li><li>For each symbol, the linker calculates an address in this image.</li><li>Then it applies the relocations defined for every symbol. It is easy now, since the linker knows the exact addresses of all other symbols referenced from those relocations.</li><li>The linker prepares all the headers necessary for the <a href="http://en.wikipedia.org/wiki/Executable_and_Linkable_Format">Executable and Linkable (ELF)</a> format (on Linux) or the <a href="http://en.wikipedia.org/wiki/Portable_Executable">Portable Executable (PE)</a> format (on Windows). Then, it generates an executable file with the results.</li></ul><h3><strong>Intermediate Representation</strong></h3><p>You may be wondering what exactly is meant by “intermediate representation”. Well, simply put, it is the code that is used internally by the compiler to represent source code. You can think of three layers for which in our case, the Go source code layer is at the top and at the bottom we have the target layer which is the machine code. In between these two, is the intermediate representation layer (IR for short), hence the term “intermediate”. So in essence, the Go compiler takes your .go file, and then generates an object file that contains assembly instructions.</p><p>Generally, a compiler would generate a syntax-tree based IR. However, Go uses a more modern static-single assignment (SSA) IR. This means that a program is in static single assignment if there is only one assignment per variable in the program. If the program does not follow this single assignment requirement then a variable renaming process is initiated. For example, if x is defined twice, then this process would rename them as x1 and x2.</p><p>Go had been previously using a syntax-tree based IR, but as of the release of Go 1.7 has been using an SSA based IR for amd64 architectures and as of Go 1.8 SSA based IR has been incorporated for the rest of the architectures. The goal of making the switch to this new SSA based IR was to generate programs that were more efficient both in size and speed.</p><p>Just to reiterate, prior to SSA, the Go compiler would take the syntax tree and perform different tasks beginning with type checking, closure analysis, and ending with the code generation step. Rather than reinventing the wheel and replacing the compiler completely, now the code generation step has been replaced with SSA. What this step now does is take the syntax tree and turn into an SSA representation, performing optimizations on it, and finally turning it back into assembly to build the object file. Some of the optimization algorithms used by SSA are:</p><ul><li>Common Subexpression Elimination</li><li>Dead Code Elimination</li><li>Dead Store Elimination</li><li>Nil Check Elimination</li><li>Register allocation</li></ul><p>Now let’s find out how we can see the SSA generated from our Go code. We will be using a simple program with an if statement.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aef1f253844e39d9eb78e81d03cb86cd/href">https://medium.com/media/aef1f253844e39d9eb78e81d03cb86cd/href</a></iframe><p>You can run it using go run example.go and your output will of course be a is not equal to b.</p><p>You can then use the following command to begin the SSA process.</p><pre>env GOSSAFUNC=main go build example.go &amp;&amp; open ssa.html</pre><p>Here, we are setting the environment variable GOSSAFUNC to the function name we want to print the SSA representation and building our Go file, and opening the ssa.html file generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fqnb4R1-jOBU9iezBPLHpA.png" /><figcaption>ssa.html</figcaption></figure><p>This will show you the optimization passes the Go compiler has done to your code with a very nice visualization.</p><p>In order to view the SSA representation of your input we can use either the ssadump command or a very wonderful online SSA viewer that will yield the same result and can be found <a href="https://golang-ssaview.herokuapp.com/">here</a>. If you don’t have the ssadump command you will have to install it depending on your OS. I am on Mac, so I installed it through ActiveGo <a href="https://www.activestate.com/products/activego/downloads/">here</a>. They have installers for Windows, Mac, and Linux.</p><p>While in the directory where example.go is located, go ahead and run this command in the terminal: ssadump -build=CPF example.go. This will output the following SSA generated code given our example.go file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64bdef5f07d65144f456189327c4eb7d/href">https://medium.com/media/64bdef5f07d65144f456189327c4eb7d/href</a></iframe><p>As you can see, SSA has generated what looks like a combination Go code mixed with assembly. It has created four blocks of code, and execution begins func main() where it says entry P:0 S:2 to the right. Another thing to note is how the variables are renamed, to keep in line with single assignment property. In the end, this should give you a clear idea of what goes on under the hood, and show you what the flow of your program is.</p><h3>Authors</h3><p>Raul Rios, Zhuo Ai, <a href="https://github.com/thomasjoel">Joel Thomas</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83b8c93268a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[200m Dive with Go]]></title>
            <link>https://medium.com/@plp.project2019/200m-dive-with-go-91ea05921bdf?source=rss-a16afe2a45c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/91ea05921bdf</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[UH PLP]]></dc:creator>
            <pubDate>Wed, 20 Mar 2019 16:55:20 GMT</pubDate>
            <atom:updated>2019-03-20T16:55:20.849Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*xigEPm_IYX8dY6y8JiyrKA.gif" /></figure><blockquote>(Fun fact: The deepest free dive record is held by Herbert Nitsch at a depth of 253m / 831ft.)</blockquote><p>We pick up where we left off in our last post (found <a href="https://medium.com/@plp.project2019/diving-deeper-with-go-44a7baf3cb2e">here</a>) in which we talked about the Data Types, Expressions and Data abstraction available in Golang.</p><p>In this post, we cover some of the debugging, support and testing frameworks that are available for Go.</p><h3>Debugging</h3><p>There are a lot of tools that can be used to debug Go, for example, godebug, Visual Studio Code, GDB, etc. Here in this article, we will pick one tool — VS code — to demonstrate how to debug codes written in Go language.</p><p>Before we move to debugging, you need to meet the following requirements:</p><ol><li>You understand the basics of Go.</li><li>You have go installed in your machine and the environment variable $GOPATH is set. (It defaults to ~/go)</li><li>The path $GOPATH/bin is exposed to your PATH.</li><li>You have Visual Studio Code installed.</li><li>You should have the VS Code-Go plugin installed.</li></ol><p>Once you have this installed, when open any .go files in VSCode, you will be prompted on the bottom right of the status bar to Install Analysis Tools, and you should click on that link to install the necessary Go packages for the plugin to work efficiently.</p><p>We finally need to install a debugger for Go, called <a href="https://github.com/derekparker/delve">Delve</a>. It’s an open source project. To do this, there are <a href="https://github.com/derekparker/delve/wiki/Installation">detailed installation instructions for specific platforms</a>. For Mac user, it’s as straightforward as:</p><pre>Brew install go-delve/delve/delve</pre><p>After you meet you all the requirements mentioned above, you will be able to debug any Go language using VS code. Here is a short introduction on how to get started debugging your Go program.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F7SeF3-OQ6RQ%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D7SeF3-OQ6RQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F7SeF3-OQ6RQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba710860f205c8aa6e13d19e7995d521/href">https://medium.com/media/ba710860f205c8aa6e13d19e7995d521/href</a></iframe><p>Source code (main.go) used in the video is attached below:</p><pre>package main</pre><pre>import (<br>    &quot;encoding/json&quot;<br>    &quot;fmt&quot;<br>    &quot;log&quot;<br>)</pre><pre>// Avenger represents a single hero<br>type Avenger struct {<br>    RealName string `json:&quot;real_name&quot;`<br>    HeroName string `json:&quot;hero_name&quot;`<br>    Planet   string `json:&quot;planet&quot;`<br>    Alive    bool   `json:&quot;alive&quot;`<br>}</pre><pre>func (a *Avenger) isAlive() {<br>    a.Alive = true<br>}</pre><pre>func main() {<br>    avengers := []Avenger{<br>        {<br>            RealName: &quot;Dr. Bruce Banner&quot;,<br>            HeroName: &quot;Hulk&quot;,<br>            Planet:   &quot;Midgard&quot;,<br>        },<br>        {<br>            RealName: &quot;Tony Stark&quot;,<br>            HeroName: &quot;Iron Man&quot;,<br>            Planet:   &quot;Midgard&quot;,<br>        },<br>        {<br>            RealName: &quot;Thor Odinson&quot;,<br>            HeroName: &quot;Thor&quot;,<br>            Planet:   &quot;Midgard&quot;,<br>        },<br>    }</pre><pre>avengers[1].isAlive()</pre><pre>jsonBytes, err := json.Marshal(avengers)<br>    if err != nil {<br>        log.Fatalln(err)<br>    }<br>    fmt.Println(string(jsonBytes))<br>}</pre><h3>Unit Testing Framework</h3><p>Testing is an integral part of writing code. It ensures quality and improves reliability in the program. Let’s look at a few testing frameworks available in Golang. To demonstrate the usage of testing frameworks, the code doesn’t have to be complicated. We will use a simple calculator implementation providing exported functions for addition, subtraction, multiplication and division.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ee121e6af6b02e93fd87e94f92b2b6f/href">https://medium.com/media/0ee121e6af6b02e93fd87e94f92b2b6f/href</a></iframe><h4>Package Creation and Exporting variables</h4><p>There are a few things to note in the code above. The main calculator implementation is in the package calc whereas all testing code will be in the package calc_test (seen below). This separation helps to ensure that the package is being used via the exported API. You can also put the testing files in the same package but be sure to name the package the same in the first line.</p><p>Creating a package is simple as creating a new directory in %GOPATH% with a *.go file in it. Additionally, all testing files must end with a _test suffix. From the documentation found <a href="https://golang.org/doc/code.html#Testing">here</a>.</p><blockquote>You write a test by creating a file with a name ending in _test.go that contains functions named TestXXX with signature func (t *testing.T). The test framework runs each such function; if the function calls a failure function such as t.Error or t.Fail, the test is considered to have failed.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*PtRcd1kgKNEr9gH4ALX-iQ.png" /></figure><p>Finally, in Golang, variables or functions that start with an UPPERCASE letter can be exported while variables that start with a LOWERCASE letter are private to the package.</p><h4>Golang Testing Package</h4><p>We start by looking at the testing package that comes with Golang’s standard library. This library is easy to navigate however it can become repetitive.</p><p>First import the calc and testing packages. Pay special attention to the dot notation before “calc”. In some cases, importing a package without the dot notation, led to the package being imported but not used.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4107f1bdac18b459d82f09fb61b02a1b/href">https://medium.com/media/4107f1bdac18b459d82f09fb61b02a1b/href</a></iframe><p>We can run the test with the following command: go test -v ./calc_test</p><p>The -v is a flag that stands for verbose.</p><pre>=== RUN   TestAddWithTestingPackage</pre><pre>--- PASS: TestAddWithTestingPackage (0.00s)</pre><pre>=== RUN   TestSubtractWithTestingPackage</pre><pre>--- PASS: TestSubtractWithTestingPackage (0.00s)</pre><pre>=== RUN   TestMultiplyWithTestingPackage</pre><pre>--- PASS: TestMultiplyWithTestingPackage (0.00s)</pre><pre>=== RUN   TestDivideWithTestingPackage</pre><pre>--- PASS: TestDivideWithTestingPackage (0.00s)</pre><pre>PASS</pre><pre>ok      command-line-arguments  0.371s</pre><h4>Testify</h4><p>Testify is an assertion and mocking toolkit that works well with the standard testing package. The assert package provides helpful functions for asserting the expected outcome of a test case. It improves readability of the code as well. It is one of the most popular testing toolkits for Golang.</p><blockquote>Note: Be sure to install the toolkit first using go get github.com/stretchr/testify/assert and then import the package.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0518ec713cd985213b88b7ebf80e6320/href">https://medium.com/media/0518ec713cd985213b88b7ebf80e6320/href</a></iframe><p>Typically, all tests in a package should be run but for the purposes of this tutorial we can run a specific test file at a time by referencing the name of that file:</p><p>go test -v ./calc_test/calc_testify_test.go</p><p>The test produces the same console output as the standard testing does.</p><h4>Go-testdeep</h4><p>This is a useful framework for comparing values in data structures. It offers certain operators to avoid repetition of common comparison functionality. For example, you can compare the contents of a map or check if the value of a number is greater or equals than the expected value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/957439b518c833f875d69e454b9b605e/href">https://medium.com/media/957439b518c833f875d69e454b9b605e/href</a></iframe><p>Since the calculator code isn’t very complex, it does not sufficiently showcase this toolkit’s full capabilities. Sample output if a failure occurs:</p><pre>=== RUN   TestAddWithGoTestDeep<br>--- FAIL: TestAddWithGoTestDeep (0.00s)<br>	calc_gotestdeep_test.go:12: Failed test<br>		*DATA: values differ<br>			     got: (int) 3<br>			expected: (int) 2<br>		[under TestDeep operator Ptr at calc_gotestdeep_test.go:12]<br>FAIL<br>exit status 1<br>FAIL	command-line-arguments	0.431s</pre><p>That was a short look into some of the unit testing frameworks available for Golang. For a more comprehensive list or to learn more, click this <a href="https://bmuschko.com/blog/go-testing-frameworks/">link</a>.</p><h3>Testing Support</h3><p>In this section, we will be explaining a bit more about Golang’s <em>testing</em> package. Golang’s testing package provides support for automated testing, logging and error reporting. It also contains some functionality for benchmarking functions.</p><p><em>gotest</em> is a Unix bash script so under Windows you need a MINGW environment. (see <a href="https://bitbucket.org/akavel/gowin-env/downloads/">https://bitbucket.org/akavel/gowin-env/downloads/</a>)</p><p>To (unit-)test a package you write a number of tests that you can run frequently (after every update) to check the correctness of your code. We need to write a set of Go source files which will exercise and test our code. These test-programs must be within the same package and the files must have names of the form <em>*_test.go</em>, so the test code is separated from the actual code of the package.</p><p>Note that these <em>_test</em> programs are not compiled with the normal Go-compilers. Only <em>gotest</em> compiles normal programs and the test-programs.</p><p>In the <em>*_test.go</em> files, we must include <strong>import “testing”</strong> at the top of the file. Global functions are written starting with <strong>TestAbc</strong>, where <strong>Abc </strong>is an alphabetic description of the function to be tested e.g. TestFmtInterface, TestPayEmployees, etc.</p><p>Global functions should have a header of the form:</p><p><strong>func TestAbcde(t *testing.T)</strong></p><p>where T is a struct type passed to the Test functions that manages test state and supports formatted test logs, like t.Log, t.Error, t.ErrorF, etc.</p><p>At the end of each of these functions the output is compared with what is expected and if these are not equal an error is logged. A successful test function returns successfully.</p><p>To signal a failure we have:</p><p><strong>func (t *T) Fail()</strong></p><p>which marks the test function as <strong>having failed, but continues its execution</strong>.</p><p><strong>func (t *T) FailNow()</strong></p><p>which marks the test function as <strong>having failed and stops its execution</strong>. All other tests in this file are also skipped, execution continues with the next test file.</p><p><strong>func (t *T) Log(<em>args</em> …interface{})</strong></p><p>the <strong><em>args</em></strong> are formatted using default formatting and the text is logged in the error-log.</p><p><strong>func (t *T) Fatal(args …interface{})</strong></p><p>has the combined effect of <strong>func (t *T) Log(args …interface{})</strong> followed by <strong>func (t *T) FailNow()</strong></p><p><em>go test</em> compiles the test-programs, and executes all the <em>TestAbc</em>-functions in the test programs. If all tests are successful the word <strong>PASS</strong> will be printed.</p><p><em>go test</em> can also take 1 or more test programs as parameters, and some options.</p><p>When <em>gotest</em> is given the <em>–chatty</em> or <em>-v</em> options, each test function that is run is mentioned and its test-status is printed to the console.</p><pre>go test fmt_test.go — chatty</pre><pre>=== RUN fmt.TestFlagParser</pre><pre>— — PASS: fmt.TestFlagParser</pre><pre>=== RUN fmt.TestArrayPrinter</pre><pre>— — PASS: fmt.TestArrayPrinter</pre><pre>…</pre><h4>Benchmarking</h4><p>The testing package also contains some types and functions for simple benchmarking. The <em>*_test.go</em> file must contain function(s) that start with <strong><em>BenchmarkZzz</em></strong> and take a parameter of type <em>*testing.B</em></p><p>For example:</p><p><strong>func BenchmarkReverse(b *testing.B) {</strong></p><p><strong>…</strong></p><p><strong>}</strong></p><p>Use the command</p><pre>go test -test.bench=.*</pre><p>to execute all of these functions. If the functions are called with <em>testing.Benchmark</em>, you can also simply run the program.</p><p>Finally, testing uses concrete cases of input and so we can never test <strong>all</strong> cases.</p><p>Thus, we must consider:</p><p>• a normal case</p><p>• abnormal cases (wrong input like negative numbers or letters instead of numbers, no input)</p><ul><li>boundary cases (if a parameter has to have a value in the interval 0–1000, then check 0 and 1000)</li></ul><h4>Authors</h4><p><a href="https://github.com/thomasjoel">Joel Thomas,</a> <a href="https://github.com/garcialeonel">Leonel Garcia,</a> Zhuo Ai, Raul Rios</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91ea05921bdf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Diving Deeper With Go]]></title>
            <link>https://medium.com/@plp.project2019/diving-deeper-with-go-44a7baf3cb2e?source=rss-a16afe2a45c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/44a7baf3cb2e</guid>
            <category><![CDATA[expression]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[data-type]]></category>
            <category><![CDATA[control-abstraction]]></category>
            <dc:creator><![CDATA[UH PLP]]></dc:creator>
            <pubDate>Mon, 25 Feb 2019 06:54:11 GMT</pubDate>
            <atom:updated>2019-02-25T06:54:11.899Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*ERojGMB35dNDZJtgdC-iFw.png" /></figure><blockquote>This is a continuation of our previous post where we introduced you to the Go programming language and got your environment set up. If you like to visit that post please click <a href="https://medium.com/@plp.project2019/getting-started-with-go-1aae65b98fb2">here</a>. We walked you through both Linux and Windows installations and then gave an overview of the package management system in Go, which has seen quite a rapid evolution in the past years.</blockquote><p>In this post, we will be walking you through an overview of the following four topics:</p><ol><li>Control Abstraction</li><li>Data Types</li><li>Data Abstraction</li><li>Expressions</li></ol><h3><strong>Control Abstraction</strong></h3><p><strong>Abstraction</strong> is a mechanism to hide irrelevant details and represent only the essential features so that one can focus on important things at a time; It allows managing complex systems by concentrating on the essential features only. Abstraction can be of two types, namely, <em>data abstraction </em>and <em>control abstraction. </em><strong>Data abstraction</strong><em> </em>means hiding the details about the data and <strong>control abstraction </strong>means hiding the implementation details.</p><p>Golang is quite capable of implementing higher-level abstractions, but the language designers chose not to implement certain abstractions into the programming language itself. You can use interfaces to create common abstractions that can be used by multiple types. Interfaces define one or more method declarations that must be satisfied to be compatible with the interface. An example is presented as follows:</p><pre>package main <br>import &quot;fmt&quot;<br>// Define a new data type &quot;Triangle&quot;<br>type Triangle struct {<br>	base, height float32<br>}<br>// Define a new data type &quot;Square&quot;<br>type Square struct {<br>	length float32<br>}<br>// Define a new data type &quot;Rectangle&quot;<br>type Rectangle struct {<br>	length, width float32<br>}<br>// Define a new data type &quot;Circle&quot;<br>type Circle struct {<br>	radius float32<br>}<br>// A method for type &quot;Triangle&quot;<br>func (t Triangle) Area() float32 {<br>	return 0.5 * t.base * t.height<br>}<br>// A method for type &quot;Square&quot;<br>func (l Square) Area() float32 {<br>	return l.length * l.length<br>}<br>// A method for type &quot;Rectangle&quot;<br>func (r Rectangle) Area() float32 {<br>	return r.length * r.width<br>}<br>// A method for type &quot;Circle&quot;<br>func (c Circle) Area() float32 {<br>	return 3.14 * (c.radius * c.radius)<br>}<br>// Define an interface as achieve abstraction<br>type Area interface {<br>	Area() float32<br>}<br>func main() {<br>	// Declare and assign values to varaibles<br>	t := Triangle{base: 15, height: 25}<br>	s := Square{length: 5}<br>	r := Rectangle{length: 5, width: 10}<br>	c := Circle{radius: 5}<br> <br>	// Define a variable of type interface<br>	var a Area<br> <br>	// Assign to the interface a variable of type &quot;Triangle&quot;<br>	a = t<br>	fmt.Println(&quot;Area of Triangle&quot;, a.Area())<br> <br>	// Assign to the interface a variable of type &quot;Square&quot;<br>	a = s<br>	fmt.Println(&quot;Area of Square&quot;, a.Area())<br> <br>	// Assign to the interface a variable of type &quot;Rectangle&quot;<br>	a = r<br>	fmt.Println(&quot;Area of Rectangle&quot;, a.Area())<br> <br>	// Assign to the interface a variable of type &quot;Circle&quot;<br>	a = c<br>	fmt.Println(&quot;Area of Circle&quot;, a.Area())<br>}</pre><h3>Data Types</h3><p>Like any other programming language, Go has a set of data types from which you use as building blocks in your program. So what exactly are data types you may ask? Well, data types help you (the programmer) define how data is stored in memory, the possible values that a variable may hold, and what operations can be done on that data.</p><p>We can classify the basic data types in three groups which are numeric, boolean, and string types. You can then take these basic data types and use them to define higher level types such as structs, arrays, slices, and maps. If you have experience with another programming language already then most of this may already appear familiar to you, but a nice refresher never hurts! :D</p><h4>Numeric</h4><p>We can classify numeric data types into three different types which are Integer, Floating-point, and Complex types.</p><p><strong><em>Integer</em></strong> types can be used to store whole numbers. As such, Go provides a wide variety of unsigned and signed types accommodating a variety of sizes.</p><p>Both int and uint are platform dependent but the following describes the ranges the other integer data types are able to handle.</p><pre>int8: for 8 bit integers covering a range from -128 to 127<br>int16: for 16 bit integers covering a range from -2^15 to (2^15)-1<br>int32: for 32 bit integers covering a range from -2^31 to (2^31)-1<br>int64: for 64 bit integers covering a range from -2^63 to (2^63)-1</pre><pre>uint8: for 8 bit integers covering a range from 0 to 255<br>uint16: for 16 bit integers covering a range from 0 to (2^15)-1<br>uint32: for 32 bit integers covering a range from 0 to (2^32)-1<br>uint64: for 64 bit integers covering a range from 0 to (2^64)-1</pre><p>Additionally, since there is no char data type like in C, Go provides us with two additional data types which are byte and rune . These are both used to represent ASCII and Unicode characters respectively. Internally, a byte is an alias touint8 and a rune is an alias for int32. A variable assigned a character has a default value of rune unless explicitly stored as a byte. Furthermore, any uninitialized integer defaults to 0.</p><pre>Example:<br>var count int            // count is initialized with 0<br>var count int = 1        // count is initialized with 1<br>var firstInitial = &#39;R&#39;   // inferred to be of type rune</pre><p>Moving onto <strong><em>Floating-point</em></strong> types which allow us to store decimal numbers such as dollar amounts or the value of pi. Go provides us with a couple of floating types which arefloat32 and float64 each of which is able to represent IEEE-754 32-bit and 64-bit floating point numbers respectively. Any uninitialized floating type has a default value of 0. You are able to define them in one of two ways:</p><pre>Explicit Decimals<br>var randNum float64 = 1.23456789</pre><pre>OR</pre><pre>Decimals with exponent<br>var randNum float64 = 1.123456e+5        // evaluates to 112345.6</pre><p>Our third number type is the <strong>Complex</strong> type. You can declare a complex type by usingcomplex64 and complex128 which can be seen as an extension of both float32 and float64 types with respectively. However, the default type for a complex type is complex128.</p><pre>var n = -5.25 + 5i      //type of complex128 with value: (-5.25+12i)</pre><h4>Boolean</h4><p>Go also provides us with a <strong>boolean</strong> data type that is used to represent a value of either true or false. They can be declared like so:</p><pre>var isTrue = true<br>OR<br>var isFalse bool = false</pre><h4>Strings</h4><p>To wrap up this section on data types,<strong> strings </strong>in Go are represented as an immutable sequence of bytes. What this means, is that once you create a string variable, you are not able to change the contents of that string. You would need to create a string from the contents of your old string if you wanted to manipulate it. You are able to define a utf8 encoded string as a normal string or a raw string that allows you to assign multiline unencoded text. A normal string is specified with double quotes and a raw string is specified with a pair of backticks.</p><pre>var message = &quot;Hello World&quot;<br>OR<br>var message = `Hello World! Go is a really really really<br>               awesome language!`</pre><p>It is important to note that normal strings are not able to contain newlines, but are able to contain escape characters such \n or \t. A raw string, however, ignores escape characters and takes them as being part of the string.</p><h3><strong>Data Abstraction</strong></h3><p>Data abstraction allows for the organization of programs into understandable pieces of code. Data abstraction is a way to organize the use of data structures according to the rules guaranteeing that the data structures are used correctly. This helps in achieving clarity, maintenance, and scalability. It makes it possible to improve a language’s quality and can even be used to define a new language on top of the currently existing one.</p><h4>Example</h4><p>In order to make use of the idea of data abstraction in Go, we must use <em>interfaces</em>. Go is <strong>not</strong> an object-oriented programming language: it does not make use of classes and inheritance. But it does include the concept of interfaces which can help bring some ideas from OOP into Go. Interfaces can use various defined types.</p><p>The format of an interface is this:</p><pre><strong>type </strong>Namer <strong>interface </strong>{ <br>Method1(param_list) return_type<br>Method2(param_list) return_type …<br>}</pre><p>For our example in demonstrating abstraction, we will first create a program to show how <em>structures</em> and <em>methods</em> work in Go. Our program will display the power level and abilities of two characters in a video game.</p><pre>package main<br>import &quot;fmt&quot;</pre><pre>type Character <strong>struct</strong> {<br>    powerlevel int<br>    ability string<br>}</pre><pre>func (c *Character) create(pl int, ab string) {<br>    c.powerlevel = pl<br>    c.ability = ab<br>}</pre><pre>func main() {<br>    // initialize and assign a new Character object<br>    creator := new(Character)</pre><pre>// create a monster<br>    creator.create(5, &quot;I am a Monster. I eat critters.&quot;)<br>    fmt.Println(&quot;Monster character&#39;s attributes&quot;)<br>    fmt.Println(&quot;\tPower level: &quot;, creator.powerlevel)<br>    fmt.Println(&quot;\tAbility: &quot;, creator.ability, &quot;\n&quot;)</pre><pre>// create a critter<br>    creator.create(1, &quot;I am a Critter. I get eaten by Monsters.&quot;)<br>    fmt.Println(&quot;Critter character&#39;s attributes&quot;)<br>    fmt.Println(&quot;\tPower level: &quot;, creator.powerlevel)<br>    fmt.Println(&quot;\tAbility: &quot;, creator.ability)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*L_uIK-JaichxIVbtBRWlJg.png" /><figcaption>Output of above program</figcaption></figure><p>This shows how to utilize the idea of “<em>classes</em>” and “<em>methods</em>” in Go.</p><p>We first created a <em>Character</em> structure to define the attributes of the game’s characters: a power level or its strength, and an ability or the character’s traits. Then we created a <em>create</em>() method to create the character’s themselves.</p><p>When we incorporate <strong>interfaces, </strong>however, we can get much closer to OOP:</p><pre>package main<br>import &quot;fmt&quot;</pre><pre>type stockPosition struct {<br>    ticker string<br>    sharePrice float32<br>    count float32<br>}</pre><pre>/* method to determine the value of a stock position */<br>func (s stockPosition) getValue() float32 {<br>    return s.sharePrice * s.count<br>}</pre><pre>type car struct {<br>    make string<br>    model string<br>    price float32<br>}</pre><pre>/* method to determine the value of a car */<br>func (c car) getValue() float32 {<br>    return c.price<br>}</pre><pre>/* contract that defines different things that have value */<br><strong>type valuable interface {<br>    getValue() float32<br>}</strong></pre><pre>/* anything that satisfies the ‚&quot;valuable&quot; interface is accepted */<br>func showValue(asset <strong>valuable</strong>) {<br>    fmt.Printf(&quot;Value of the asset is %f\n&quot;, asset.getValue())<br>}</pre><pre>func main() {<br>    var o valuable = stockPosition{ &quot;GOOG&quot;, 577.20, 4 }<br>    showValue(o)<br>    o = car{ &quot;BMW&quot;, &quot;M3&quot;, 66500 }<br>    showValue(o)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*Wpa7tumCvY9gOwvaHTGPLw.png" /><figcaption>Output of above program</figcaption></figure><p>We have two types: <strong>stockPosition</strong> and <strong>car</strong>. Both have the method <em>getValue</em>(). We can define a new interface called <strong>valuable</strong> using the method <em>getValue</em>(). We can also create methods that take a parameter as a <strong>valuable</strong> type. Thus, all types that implement <strong>valuable</strong> as a parameter can also use it in its own method such as the <em>showValue</em>() method for example.</p><p>Go has no classes but rather uses types and their methods implementing interfaces.</p><blockquote>Sources:</blockquote><blockquote>“The Way to Go: A Thorough Introduction to the Go Programming Language” by Ivo Balbaert <a href="https://tinyurl.com/y64k4q5w">(https://tinyurl.com/y64k4q5w</a>)</blockquote><blockquote>“Programming Paradigms for Dummies: What Every Programmer Should Know” by Peter Van Roy</blockquote><h3><strong>Expressions</strong></h3><p>An expression in a programming language is a combination of one or more operators, variables, and functions that the language interprets and computes to produce another value. In simple scenarios, these are usually numeric, string, logical etc. leading to more complex data types.</p><p>Examples:</p><pre>2+2             //evaluates to 4</pre><pre>X == Y         //logical expression</pre><pre>s[i : j + 1] //slice expression</pre><pre>obj.color      //method calls</pre><h4>Operators</h4><p>Operators combine operands into expressions. Go supports the main operators seen in various programming languages.</p><h4>Arithmetic operators</h4><p>Arithmetic operators apply to numeric values and yield a result of the same type as the first operand. The four standard arithmetic operators (+, -, *, /) apply to integer, floating-point, and complex types; + also applies to strings. The bitwise logical and shift operators apply to integers only</p><pre>+ sum integers, floats, complex values, strings<br>- difference integers, floats, complex values<br>* product integers, floats, complex values<br>/ quotient integers, floats, complex values<br>% remainder integers</pre><p>Examples:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br><br>   var a int = 21<br>   var b int = 10<br>   var c int<br><br>   c = a + b    //31<br>   <br>   c = a - b    //11<br>   <br>   c = a * b   //210<br>     <br>   c = a / b   //2<br>     <br>   c = a % b   //1<br>   <br>}</pre><h4>String concatenation</h4><p>Strings can be concatenated using the + operator or the += assignment operator. String addition creates a new string by concatenating the operands:</p><pre>s := “hi” + string(c)<br>s += “ and good bye”</pre><h4>Comparison operators</h4><p>Comparison operators compare two operands and yield an untyped boolean value.</p><pre>==    equal<br>!=    not equal<br>&lt;     less<br>&lt;=    less or equal<br>&gt;     greater<br>&gt;=    greater or equal</pre><p>In any comparison, the first operand must be assignable to the type of the second operand, or vice versa.</p><p>The equality operators == and != apply to operands that are comparable. The ordering operators &lt;, &lt;=, &gt;, and &gt;= apply to operands that are ordered.</p><p><strong>This single rule significantly narrows the scope of possible options</strong>:</p><pre>var a int = 1<br>var b int = 2<br>var c float32 = 3.3<br>var d float32 = 4.4</pre><pre>fmt.Println(a == b) // false<br>fmt.Println(a == d)</pre><p>a == d would throw an error during compilation (mismatched types int and float32) so it isn’t possible to compare float with int.</p><h4>Logical operators</h4><p>Logical operators apply to boolean values and yield a result of the same type as the operands. The right operand is evaluated conditionally.</p><pre>&amp;&amp;    conditional AND    p &amp;&amp; q  is  &quot;if p then q else false&quot;<br>||    conditional OR     p || q  is  &quot;if p then true else q&quot;<br>!     NOT                !p      is  &quot;not p&quot;</pre><p>Example:</p><pre>package main<br>import &quot;fmt&quot;</pre><pre>func main() {</pre><pre>var a bool = true<br>var b bool = false</pre><pre>if ( a &amp;&amp; b ) {<br>  fmt.Printf(&quot;Line 1 - Condition is true\n&quot; )<br>}</pre><pre>if ( a || b ) {<br>  fmt.Printf(&quot;Line 2 - Condition is true\n&quot; )<br>}</pre><p>When you compile and execute the above program it produces the following result −</p><pre>Line 2 - Condition is true</pre><h4>Method expressions</h4><p>Go does not have classes. However, you can define methods on types. This is known as <strong>method expressions</strong>. A method is a function with a special <em>receiver</em> argument. The receiver appears in its own argument list between the func keyword and the method name.</p><p>In the example below, the Abs method has a receiver of type Vertex named v.</p><pre>package main<br>import (<br>&quot;fmt&quot;<br>&quot;math&quot;<br>)</pre><pre>type Vertex struct {<br>   X, Y float64<br>}</pre><pre>func (v Vertex) Abs() float64 {<br>   return math.Sqrt(v.X*v.X + v.Y*v.Y)<br>}</pre><pre>func main() {<br>  v := Vertex{3, 4}<br>  fmt.Println(v.Abs())<br>}</pre><p>You can declare a method on non-struct types, too: type MyFloat float64</p><p>You can also declare methods with pointer receivers. This means the receiver type has the literal syntax *T for some type T. (However, T cannot itself be a pointer such as *int.)</p><p>Using the previous example:</p><pre>func (v *Vertex) Scale(f float64) {<br>  v.X = v.X * f<br>  v.Y = v.Y * f<br>}</pre><pre>func main() {<br>  v := Vertex{3, 4}<br>  v.Scale(10)<br>  fmt.Println(v.Abs())<br>}</pre><blockquote>Other forms of expressions can be seen in variadic functions, slice expressions, constant expressions. These are just few examples from a comprehensive list which are detailed in the specifications <a href="https://golang.org/ref/spec#Expressions">here</a>.</blockquote><p>Authors:</p><p>Leonel Garcia Jr., Raul Rios, Zhuo Ai, Joel Thomas</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44a7baf3cb2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Go]]></title>
            <link>https://medium.com/@plp.project2019/getting-started-with-go-1aae65b98fb2?source=rss-a16afe2a45c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1aae65b98fb2</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[installation]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[hello-world]]></category>
            <dc:creator><![CDATA[UH PLP]]></dc:creator>
            <pubDate>Mon, 18 Feb 2019 05:52:43 GMT</pubDate>
            <atom:updated>2019-02-18T05:52:43.676Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*ERojGMB35dNDZJtgdC-iFw.png" /></figure><p><strong>Go</strong> or <strong>Golang</strong> is a programming language developed in <em>2007</em> by Robert Griesemer, Rob Pike, and Ken Thompson at Google. It was launched in <em>2009</em> as an open source programming language. The main motivation is to simplify systems programming and to make programming fun again. Go is a relatively new language that is in constant development, but it already has a considerable amount of industry support and it has been used in a lot of real systems at Google. This article aims to introduce developers to Go and give them enough information to try it out for themselves.</p><h3>Installation on Linux</h3><p>First, we will be learning how to install Go on Linux. More specifically, we will learn how to install Go on a machine running Ubuntu 18.04. Ubuntu is one of the most commonly used Linux distributions. Like most Linux distros, Ubuntu is free to download at <a href="https://www.ubuntu.com/#download"><strong>ubuntu.com/#download</strong></a>. The steps laid out<br>here can also work on most Debian-like Linux distros. We will utilize some terminal commands. There is no command line expertise required. I&#39;ll post the commands here.</p><h4>Download Linux Binary File</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*68vib2hrNPbh7PMrKXXl7w.gif" /></figure><p>First, download the linux binary file from the Go website at <a href="https://golang.org/dl/"><strong>golang.org/dl</strong></a><br>Under <em>Featured Downloads</em> hover over to the Linux box and click on <strong>goX.X.X.linux-amd64.tar.gz </strong>(depending on the current go version)</p><p>When the prompt shows up, select <strong><em>Save File </em></strong>and choose where the archive should be saved to (typically in ~/Downloads but in this case I chose ~/Documents)</p><h4>Extract Contents</h4><p>Launch Terminal and enter</p><p>sudo tar -C /usr/local -xzf go1.11.5.linux-amd64.tar.gz<br>to extract the contents into <strong><em>/usr/local</em></strong>. It is important that you run this command as root since you will be accessing directories under the root path.<br>The <strong><em>-C</em></strong> option of the above command is to specify a path to extract to.<br> <strong><em>-x</em></strong> represents <strong>extract</strong><br><strong><em> -z</em></strong> tells tar that this is a gzip file<br>and <strong><em>-f </em></strong>is to specify the file <strong>goX.X.X.linux-amd64.tar.gz as the </strong>target archive file.<br>After you successfully extracted the contents of the file run</p><p>whereis go</p><p>to check whether the contents were extracted in the proper directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*B_wUl4RvAugxZSp-Iu_fkQ.gif" /></figure><h4>Add Go To Your PATH.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*uBkYBad5sSlQFCt8aqKZug.gif" /></figure><p>Next we will add <strong>/usr/local/go</strong> to our PATH enviroment variable.<br>To do this edit your <strong><em>.profile</em></strong> or <strong><em>.bash_profile</em></strong> or <strong><em>.bashrc</em></strong> file with your desired text editor (in this case I used vim and chose .profile).<br>Add the following line</p><p>export PATH=$PATH:/usr/local/go/bin<br><br>Next, go back to your terminal and run</p><p>. .profile</p><p>or</p><p>source .profile</p><p>to reset the terminal and make your changes permanent.<br>Finally check to see if your changes were successful by running</p><p>which go<br>This command should locate go in your path.</p><h4>Test Successful Installation of Go</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*0aSB7YAAOvwy7Gx_nrF1HA.gif" /></figure><p>We will finally test our Go environment is successful.<br>First, set up a workspace directory for go.</p><p>mkdir ~/go<br>Then create a new directory inside your workspace called src</p><p>cd go; mkdir src<br><br>Inside src, create a directory called hello to build a program in.</p><p>cd src &amp;&amp; mkdir hello; cd hello<br><br>Create a file called <strong><em>hello.go</em></strong> and enter</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main () {<br>    fmt.Printf(&quot;hello, world.\n&quot;)<br>}</pre><p>Next run</p><p>go build<br>to build an executable file <strong><em>hello</em></strong> in the directory along with the source code.<br>Lastly run the command with</p><pre>./hello</pre><p>Now we have successfully installed go and ran our first program on Linux!</p><h3>Installation on Windows</h3><p>1. Go to the Go downloads website <a href="https://golang.org/dl/">here</a> and download the latest version for Windows. We recommend the .msi installer for ease of use.</p><p>2. Run the installer and follow the instructions shown.</p><p>3. Next, run Command Prompt and type go version to ensure the latest version was installed. It should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*FbUDyd1WjQV6ugajigU7CQ.png" /></figure><h4>Create your work-space</h4><p>First, confirm whether the Go binaries have been added to our PATH.</p><ul><li>Right click on “Start” and click on “Control Panel”. Select “System and Security”, then click on “System”.</li><li>From the menu on the left, select the “Advanced systems settings”.</li><li>Click the “Environment Variables” button at the bottom right-hand side.</li><li>Under the System Variables section, find Path, and click Edit. Ensure it has the “C:\Go\bin” variable in it.</li></ul><p>The next step is to create our workspace. <strong>Note</strong>: this must be in a separate and new directory from where the installation files were saved, <strong><em>“C:\Go”</em></strong>.</p><p>We will create our workspace in %USERPROFILE%\Documents\Go(or <em>C:\Users\YourName\Documents\Go</em>), however you can create it wherever you like. We will also create <strong>three folders</strong> in this directory as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rO9PT367rBc6Kmi5s9nfJw.png" /></figure><h4>Create the GOPATH environment variable</h4><p>Create the GOPATH variable and reference your newly-created Go work-space.</p><ul><li>Go back to our Environment Variables window and in the “User Variables” section, click on “New”.</li><li>Type GOPATH into the “Variable name” field.</li><li>Type C:\Users\Joel Thomas\Documents\Go into the “Variable value” field and click OK.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*5DL03x9fwuk0VEw9u7pXCw.png" /></figure><p>Based on where you created your workspace, be sure to add that path to the variable value. To check that your path has been set correctly, enter echo %GOPATH% on the command line.</p><h4>Build our first program</h4><p>Next, make the directory src/hello inside your workspace, and in that directory create a file named hello.go that contains code exactly like the one we created above for Linux.</p><p>Navigate to our new hello folder and then build it with the go tool:</p><p>cd %USERPROFILE%\Documents\Go\src\hello</p><p>go build</p><p>The command above will build an executable named <em>hello.exe </em>in the directory alongside your source code. Execute it by typing hello to see the greeting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*AcPMcmWNSMLXQIinkT-I1Q.png" /></figure><h4>Editors</h4><p>I am using Sublime as a text editor of choice but there are numerous options based on your preference. Available IDE’s and text editors are explained in detail <a href="https://golang.org/doc/editors.html">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*otpOyG7Up9h1-bMoBjW9lQ.png" /></figure><h3>Package Management</h3><p>Numerous tools have been built in the past to address the issue of package management in golang. Some of these include glide, govendor, and most notably dep which was the official experiment for the Go toolchain. Now, however, as of the release of Go 1.11 versioned modules have been introduced to the Go ecosystem with Go Modules. One of the major problems Go Modules addresses that dep has is that dep disallows multiple major versions which make upgrades more difficult and can lead to builds breaking more easily.</p><p>With this in mind, a few new concepts are to be introduced:</p><p><strong>Modules</strong></p><p>A <em>module </em>is a collection of related Go packages that are versioned together as a single unit. They allow for the creation of reproducible builds by recording the dependency requirements. Although you are able to have multiple Go modules stored in a single repository, ideally each repository should contain exactly one Go module in the root. This is followed by each module being able to contain multiple Go packages where each package can consist of one or more Go source files in a single directory.</p><p>Furthermore, each Go module must be semantically versioned according to the semver standard: v(major).(minor).(patch). Specifying minor and patch is optional, but the leading v is required. This semantic versioning provides some predictability in the behavior that a developer can expect from any given Go module.</p><p><strong>go.mod</strong></p><p>The <em>go.mod</em> file exists in the root directory of the tree of Go source files. What the go.mod file essentially does is makes it so you no longer need the GOPATH, and you are able to create modules in a different directory if you want to. This is because the Go toolchain is able to understand from the go.mod file where to find everything it will need to use.</p><h4><strong>Usage</strong></h4><p>There are two ways to get started using modules:</p><ol><li>Install the latest Go 1.11 release</li><li>Install the Go toolchain from source on the master branch</li></ol><p>Once installed you can either invoke the go command with GO111MODULE=on environment variable set.</p><p><strong>Module Definition</strong></p><p>In order to create a go.mod file for an existing project you can go to the root of the module’s source tree outside of the GOPATH as shown below:</p><p>$ cd &lt;project path outside $GOPATH/src&gt; # e.g., cd ~/projects/hello</p><p>If you would like to work within your GOPATH then be sure to export the environment variable before going to the project path like so:</p><pre>$ export GO111MODULE=on               # manually active module mode<br>$ cd $GOPATH/src/&lt;project path&gt;    # e.g., cd $GOPATH/src/you/hello</pre><p>You can then create and write the module definition to the go.mod file by executing:</p><pre>$ go mod init</pre><pre>OR</pre><pre>$ go mod init github.com/my/repo # in the event that the above command states it can not determine the module path</pre><p>Finally, you can build and test your module with the following two commands from the root directory of the module:</p><pre>$ go build ./...<br>$ go test ./...</pre><p>The ./... pattern is used here to match all packages within the current module. Additionally, go build adds missing or unconverted dependencies needed to satisfy import for the build. The go test command is used to test the module configuration to ensure it works with the selected versions. If you would like to run tests for your modules and the tests for all direct and indirect dependencies you can use go test all.</p><p><strong>Upgrade and Downgrade Dependencies</strong></p><p>Commands like go build, go test, and go list automatically add new dependencies as needed to satisfy your imports by updating go.mod. In order to upgrade and downgrade dependencies, the go get command should be used, or update the go.mod file directly.</p><p>You can upgrade to the latest version for all direct and indirect dependencies of the current module by using</p><pre>$ run go get -u           # uses the latest minor or patch releases</pre><pre>OR</pre><pre>$ run go get -u=patch               # uses the latest patch releases</pre><p>To upgrade or downgrade a specific module you use the following:</p><pre>$ go get foo                     # update foo to the lastest version</pre><pre>OR</pre><pre>$ go get foo@v1.6.2              # update foo to version 1.6.2</pre><pre>OR</pre><pre>$ go get foo@e3702bed2 # update foo to version w/ commit hash prefix</pre><pre>OR</pre><pre>$ go get foo@&#39;&lt;1.6.2&#39; # update foo to the available tagged version                     <br>                      # nearest to the comparison target<br>                      # the latest version for &lt; and &lt;= <br>                      # the earliest version for &gt; and &gt;=</pre><p>Once you are done upgrading or downgrading your dependencies be sure to run go test all in order to make sure no incompatibilities are present.</p><h3>Summary</h3><p>Overall, Go is a great language that is improving fast and has shown it can be used for all project sizes. Besides, there is already a lot of open-source third-party code that can be used to complete all variety of tasks and a fairly large community to help with all kinds of questions. Obviously, I’m a big fan of Go, together with everything else introduced in this article, Go is definitely an option that you should consider if you want to pick up a new programming language.</p><h4>Authors</h4><p>Leonel Garcia, Joel Thomas, Raul Rios, Zhuo Ai, Saikrishna Ramalingam</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1aae65b98fb2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>