Friday, April 17, 2015

Day 4 - Go Packages

Today i want to check if my understandings of Go packages are correct:

(Reference: golang-packages)

1) There is only one package inside a subdirectory under $GOPATH
2) The package name has to be the same as the subdirectory name
3) The package can consist of any number of files
4) The filenames of the *.go files inside one package can be anything you choose

So i created a new directory for my test library package:

which is in my case:

Inside that directory i created two files:

1)  rpcbotinterfaceobjects_input.go

package rpcbotinterfaceobjects

type BotInput struct {
    Content string

func (this *BotInput) GetContent() string {
    return this.Content

func (this *BotInput) SetContent(NewContent string) {
    this.Content = NewContent

2)  rpcbotinterfaceobjects_output.go

package rpcbotinterfaceobjects

type BotOutput struct {
    Content string

func (this *BotOutput) GetContent() string {
    return this.Content

func (this *BotOutput) SetContent(NewContent string) {
    this.Content = NewContent

As you can see the package names are both the same, but the filenames can be anything you choose.

Next is to create the executable which uses this package in:

or in my case:

Create a file named test_my_package.go (or actually any name you want) and insert the following code into it:

package main

import (
    // use the rpcbotinterfaceobjects package

func main() {

    // Variable declaration for in and output objects
    var input rpcbotinterfaceobjects.BotInput
    var output rpcbotinterfaceobjects.BotOutput

    // Write test strings to the objects

    // Show the content of the objects

Open a cmd shell and cd into the packagetest directory.

Run  go install to build the executable, it will be put into your $GOPATH\bin folder.

Note: The bin will be named after your folder, not your *.go file!

Run packagetest

So far my assumptions 1-4 have been confirmed and additionally my tests seem to indicate that if you compile a file with func main() in it, the resulting exe is named like the directory your main comes from.

Maybe some of you may ask why I used this in the struct methods. Thats because I come from a Java and Delphi background and as this or self is not a  keyword in Go I just used it for better readability.

Golang does not have a self or this keyword to reference to the current instance. In the method example of func (c *Circle) area() float64 the receiver struct is named "c". Use that variable name, rather than this to refer to the current instance.

No comments:

Post a Comment