Categories
My Go Tutorial

Declaring a variable (Part 2

MUST be declared before using it

Order of declaring a variable in your code, here is an example of the declared variable unrecognized by fmt.Println() statement. The GO compiler (go build) took each line (reading from top to bottom) of the source code. In this case, you have a variable name odometer use but not data type and memory address defined. The compilation has failed or IDE for GO may prompt it as a problem.

// Variable declared but return error message
// when compile (go build) 
// 
func main() {
     fmt.Println(odometer)
     var odometer int
}

// Corrected code compile without error and 
// execution of code will return a value 
func main() {
     var odometer int
     fmt.Println(odometer)
}

Categories
My Go Tutorial

Declare a variable (Part 1)

MUST declare before using it

Declaration Syntax

var variable_name type

var odometer int

Naming Rules (variable names and function names)

  • 1st letter
    • a-z (1st letter)
    • _ (underscore)
    • Unicode char
  • Style
    • CamelCase
  • Special Cases
    • public accessable by other Go packages
      • A-Z (lst letter capitalize)
  • No Go’s language syntax keywords

Note: If the above rule is not followed, IDE for Go will prompt for errors, and Go run compilation will fail.

Categories
Go My Go Tutorial

Go Online Book (Free)

https://www.practical-go-lessons.com/

Categories
Interface

Interface Type

Interface names conventions

By convention, one-method interfaces are named by the method name plus an -er suffix.

type Greetinger interface {
    Greeting() string
}

Define an interface type

It start with the keyword “type” follow by the interface name (ended with -er). Begin of a block of code symbol “{“, the function name (eg. Greeting() function and return a string ). One or more than one function can be added here then is often called a method set and ending of a block of code “}”.

// https://golang.org/pkg/os/#FileInfo

type FileInfo interface {
        Name() string       // base name of the file
        Size() int64        // length in bytes for regular files; system-dependent for others
        Mode() FileMode     // file mode bits
        ModTime() time.Time // modification time
        IsDir() bool        // abbreviation for Mode().IsDir()
        Sys() interface{}   // underlying data source (can return nil)
}

In the above OS package, has FileInfo interface contains the following method sets

  • Name() string
  • Size() int64
  • Mode() FileMode
  • ModTime() time.Time
  • IsDir() bool
  • Sys() interface{}

Implementing an Interface

Categories
Go My Go Tutorial

Go (1.15.6 or later) Installation and Setup in Windows 10 (Fresh Install)

Official Go download page, this link gives you more option to choose from OS platform and OS architecture x86-64 build. And you can use the go build command parameter to building a binary for an application that can run for CPU of x86 (386) and x86-64.

https://golang.org/dl/

Install

Open the MSI file you downloaded and follow the prompts to install Go. The default folder used is C:/go. Or choose any folder that Windows 10 security may not ask for an administrator password for install programs/files using that folder path.

System Environment variable created by MSI installer

GOPATH C:\Users\loginname\go

Note: loginname is the user name to Window login

PATH C:\Go\bin

Verify

Launch a windows terminal, type go version

go version go1.15.6 windows/amd64 output confirmed go installation has been successful. Otherwise, use the Windows Control panel app -> Programs find go1.15.6 has been program has been installed.

Troubleshooting

Google, Go forum, and Stackoverflow for assistance.

https://forum.golangbridge.org/

https://stackoverflow.com/questions/tagged/go

Categories
Go My Go Tutorial

Range Over Slice and Map

package main

import "fmt"

func main() {
  kvs := map[string]string{"1":"shan kuo","2":"Hoi Leng","3":"Choi Yan","4":"Evelyn Chan"}
  for k, v := range kvs {
    fmt.Printf("%s -> %s\n",k,v)
  }
}

https://repl.it/join/gdzplzna-shankuo

 go build
 ./main
1 -> shan kuo
2 -> Hoi Leng
3 -> Choi Yan
4 -> Evelyn Chan

Categories
Go My Go Tutorial

Looping Over Arrays and Slices

package main

import "fmt"

func main() {
  names := []string{"Shank Kuo","Hoi Leng","Choi Yan","Evelyn Chan"}

  for i:=0; i < len(names); i++ {
    fmt.Println(names[i])
  }
}

https://repl.it/@shankuo/LoopArraySlice

go version go1.14 linux/amd64
 go run main.go
Shank Kuo
Hoi Leng
Choi Yan
Evelyn Chan

Categories
Data Structure and Algorithm

Slice of Slice

https://play.golang.org/p/3HpTAxoPC6l

// in Go Data Structures and algorithms book
package main

// importing fmt package
import (
	"fmt"
)

// main method
func main() {
	var rows int
	var cols int
	rows = 7
	cols = 9
	
	// rows := 7
	// cols := 9
	
 	var twodslices = make([][]int, rows)
	var i int
	for i = range twodslices {
		twodslices[i] = make([]int, cols)
	}
	fmt.Println(twodslices)
}
Categories
Data Structure and Algorithm

Create and Print a 2D Slice

https://play.golang.org/p/F5MTsF_Z1J1

// in Go Data Structures and algorithms book
package main

// importing fmt package
import (
	"fmt"
)

// main method
func main() {
	var TwoDArray [8][8]int
	TwoDArray[3][6] = 18
	TwoDArray[7][4] = 3
	fmt.Println(TwoDArray)
}
Categories
Regular Expression

Literals in Regular Expression

Literals are the simplest form of pattern matching in regular expressions. They will simply succeed whenever that literal is found.

func Match 

func Match(pattern string, b []byte) (matched bool, err error)

Match reports whether the byte slice b contains any match of the regular expression pattern.

Example Code

package main

import (
	"fmt"
	"regexp"
)

func main() {
        pattern:="Hello"
        // Match() function return a boolean type value 
        // with boolean it limit us from extracting the match string value
	matched, err := regexp.Match(pattern, []byte(`World Hello`))
	// print value return from Match() func
	fmt.Println(matched, err)
	if matched {
	   fmt.Println("Found")
	} else {
	   fmt.Println("Not Found")
	}
}

Go Playground

https://play.golang.org/p/ts3SyaxKQgF

Resources

go doc regexp/syntax

https://pkg.go.dev/regexp?tab=doc#pkg-overview