Difference between revisions of "Golang/Basics"

From Ever changing code
Jump to navigation Jump to search
(Created page with "= Main function = <source lang=golang> package main import ( "fmt" "time" ) func main() { fmt.Println("Welcome", time.Now()) } </source>")
 
 
(22 intermediate revisions by the same user not shown)
Line 11: Line 11:
}
}
</source>
</source>
= Structs (objects) =
'''Struct''' is commonly called a structure or a user define data. Structs can have [https://gist.github.com/prologic/5f6afe9c1b98016ca278f4d507e65510#methods methods]. There are different methods: methods on a struct and "pointer receiver" methods.
<syntaxhighlightjs lang=go>
package main
import "fmt"
type Student struct { // object
rollno int    //  property
name string  //  property
marks int    //  property
}
func main() {
var student1 Student = Student{101,"Piotr",55} // variable is the Student type. It's an object.
fmt.Println(student1)
fmt.Println(student1.name)
var student2 Student = Student{rollno: 102, marks: 98}
fmt.Println(student2)
fmt.Println(student2.name) // this prints empty line as
                                  // the 'name' property of the variable 'student2' has not been assigned any value
}
</syntaxhighlightjs>
<source lang=bash>
$ go run struct.go
{101 Piotr 55}
Piotr
{102  98}
</source>
== Marshal and unmarshal JSON ==
Go's terminology calls marshal the process of generating a JSON string from a data structure, and unmarshal the act of parsing JSON to a data structure.
= [https://golangbot.com/go-packages/ Go modules and custom packages] =
'''A Go Module is a collection of Go packages'''.
A module is a collection of packages that are released, versioned, and
distributed together. Modules may be downloaded directly from version control
repositories or from module proxy servers.
Why do we need Go modules to create a custom package? The answer is the import path for the custom package we create is derived from the name of the go module. In addition to this, all the other third-party packages(such as source code from github) which our application uses will be present in the <code>go.mod</code> file along with the version. This <code>go.mod</code> file is created with <code>go mod init <mymodule></code> when we create a new module.
<source lang=bash>
# in directory mymodule/ initialize a module <mymodule>
go mod init mymodule
$ cat go.mod
module mymodule
go 1.17
</source>
The <code>mymodule</code> is the base path to import any package created inside this module.
Source files belonging to a package should be placed in separate folders of their own. It is a convention(requirment) in Go to name this folder with the same name as the package. Example structure:
<source lang=bash>
mymodule -> # 'go mod init mymodule'
|- main.go # -> package "main"
|- tools
      |- helper.go # -> package "tools" as the folder name
</source>
To import tools package from main.go import this "mymodule/tools"
;Siliencers
are useful to silience errors during development:
* import a package before using it error "imported and not used"
* import a package just to make sure the initialization takes place even though we do not need to use any function or variable from the package
Silienced by using it
<source lang=go>
package main
import ( 
        "learnpackage/simpleinterest"
)
var _ = simpleinterest.Calculate
func main() {
}
</source>
Silienced import
<source lang=go>
import ( 
    _ "learnpackage/simpleinterest"
)
</source>
= <code>defer</code> =
Instruction <code>defer</code> defers the execution until all other instructions in the function complete. Multiple <code>defer</code> instructions will be executed in LIFO (last-in-first-out) order. Refer to the example below.
<source lang=go>
package main
import "fmt"
func main() {
defer printString("print 1")
printString("hey defer in action")
defer printString("print 2")
defer printString("print 3")
}
func printString(str string) {
fmt.Println(str)
}
</source>
Execute
<source lang=bash>
go run defer.go
hey defer in action
print 3
print 2
print 1
</source>
[[Category:Golang]]

Latest revision as of 21:22, 21 September 2021

Main function

package main
import (
	"fmt"
	"time"
)

func main()         {
	fmt.Println("Welcome", time.Now())
}

Structs (objects)

Struct is commonly called a structure or a user define data. Structs can have methods. There are different methods: methods on a struct and "pointer receiver" methods. <syntaxhighlightjs lang=go> package main import "fmt" type Student struct { // object rollno int // property name string // property marks int // property }

func main() { var student1 Student = Student{101,"Piotr",55} // variable is the Student type. It's an object. fmt.Println(student1) fmt.Println(student1.name)

var student2 Student = Student{rollno: 102, marks: 98} fmt.Println(student2) fmt.Println(student2.name) // this prints empty line as

                                  // the 'name' property of the variable 'student2' has not been assigned any value

} </syntaxhighlightjs>

$ go run struct.go 
{101 Piotr 55}
Piotr
{102  98}

Marshal and unmarshal JSON

Go's terminology calls marshal the process of generating a JSON string from a data structure, and unmarshal the act of parsing JSON to a data structure.

Go modules and custom packages

A Go Module is a collection of Go packages.


A module is a collection of packages that are released, versioned, and distributed together. Modules may be downloaded directly from version control repositories or from module proxy servers.


Why do we need Go modules to create a custom package? The answer is the import path for the custom package we create is derived from the name of the go module. In addition to this, all the other third-party packages(such as source code from github) which our application uses will be present in the go.mod file along with the version. This go.mod file is created with go mod init <mymodule> when we create a new module.

# in directory mymodule/ initialize a module <mymodule>
go mod init mymodule

$ cat go.mod
module mymodule
go 1.17

The mymodule is the base path to import any package created inside this module.


Source files belonging to a package should be placed in separate folders of their own. It is a convention(requirment) in Go to name this folder with the same name as the package. Example structure:

mymodule -> # 'go mod init mymodule'
 |- main.go # -> package "main"
 |- tools
      |- helper.go # -> package "tools" as the folder name

To import tools package from main.go import this "mymodule/tools"


Siliencers

are useful to silience errors during development:

  • import a package before using it error "imported and not used"
  • import a package just to make sure the initialization takes place even though we do not need to use any function or variable from the package


Silienced by using it

package main
import (  
        "learnpackage/simpleinterest"
)
var _ = simpleinterest.Calculate
func main() {
}


Silienced import

import (  
    _ "learnpackage/simpleinterest"
)

defer

Instruction defer defers the execution until all other instructions in the function complete. Multiple defer instructions will be executed in LIFO (last-in-first-out) order. Refer to the example below.

package main

import "fmt"

func main() {
	defer printString("print 1")
	printString("hey defer in action")
	defer printString("print 2")
	defer printString("print 3")
}

func printString(str string) {
	fmt.Println(str)
}


Execute

go run defer.go 
hey defer in action
print 3
print 2
print 1