Go language Learning

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

1. Package Structure and import (http://www.cnblogs.com/sunshiming/p/4928493.html)

Go language rules, under a directory, you can put more than one. Go file.

These. Go files must be the same package name, usually the same as the directory name, or it can be different.

The experiment is as follows: src/abc/    --Home directory, package must be main, must have main function func main () abc.exe*  abc.gosrc/pp/qq/  ---Library catalog Package  Uukk.go  pp.gosrc/pp/yy/  --Library catalog Package  Lulyp.go

Import pp "pp/qq"  //with PP This alias agent the package name of this directory Uu,import "Pp/yy"//The   package for this directory is lulfmt. Println (pp. F1 ()  ///here with the alias of the package FMT. Println (pp. F2 ()) fmt. Println (Lul. FF3 ())//Use the package name here

1. Go project directory structure, go build, go install, Gopath

Open git bash

$ mkdir Go3

$ export gopath=/f/gaofeng/go3/--must use export to represent environment variables, then go to read this variable, the normal variable quantum process is unreadable.

Write a package, compile it, try it.

$ go Install hesd
Can ' t load package:package hesd:cannot Find package "hesd" in any of:
D:\GO\SRC\HESD (from $GOROOT)
F:\GAOFENG\GO3\SRC\HESD (from $GOPATH)

Note that regardless of which directory the user is currently in, go goes to $goroot and $gopath's src directory to find hesd this folder to compile.

Then build the PKG1 and pkg2 two directories under SRC, write the code

$ cat Src/pkg2/abc.go
Package ABC
Import "FMT"
Func Tt () {
Fmt. Print ("Hello2")
}

Go build-v pkg2--can be compiled successfully, but cannot see the compiled pkg2.a file

Go install-v pkg2--Compile and install, automatically create the PKG directory in the GO3 directory

$ ls pkg/windows_386/
pkg2.a

$ cat Src/pkg1/m.go--Write a main package, import the PKG2 directory
Package Main
Import ("Pkg2"; FMT ")
Func Main () {
Fmt. Print ("main")
Abc. Tt ()
}

Go install-v pkg1--Compile and install successfully, automatically create the bin directory

$ ls bin/
pkg1.exe*


2. Object Programming

Func main () {var s = NewStudent2 ("Gaofeng") s.setname ("$") s.say1 ()}type say interface {Say1 () SetName (name string)}type Student struct {name String}func newstudent (name string) *student {//Returns a pointer, simply assigns a value to the interface, the interface assignment must be the address type return &student{ Name}}func NewStudent2 (name2 string) *student {return &student{name:name2}}func (S Student) Say1 () {//s is a copy, S.name = "11", just modified the temporary copy, without modifying the original object FMT. Println (S.name, "Say1")}func (S *student) SetName (name string) {//s is a pointer that can modify the object contents S.name = name}

3. Concurrent programming

Func Main () {ch1: = make (chan int) CH2: = make (chan int) go SS (CH1, 2) go SS (CH2, 4) fmt. Println (<-CH1) fmt. Println (<-CH2)}func SS (ch1 Chan int, data int) {time. Sleep (time. Second * time. Duration (data)) CH1 <-Data}

4. Defer key Words

Defer resp. Body.close () If there are multiple statements that need to be executed, you can use an anonymous function defer func () {fmt. PRINTLN ("defer")                ...} ()
5. http

import (" FMT "" "" Io "" net/http "" OS ") func Test1 () {resp, err: = http. Get ("http://www.baidu.com") if err! = Nil {fmt. Println ("ERR:", err) Return}defer resp. Body.close () Io. Copy (OS. Stdout, resp. Body)} 
Curl 127.0.0.1:8080/book?name= ' CCC ' func Main () {http. Handlefunc ("/book", handle) HTTP. Handlefunc ("/", handle2) Err: = http. Listenandserve (": 8080", nil)//If the listening service is running successfully, it is blocked here. If err! = Nil {fmt. Print (Err. Error ())}}func handle (w http. Responsewriter, R *http. Request) {time. Sleep (3 * time. Second) R.parseform ()//default not resolved, form is empty. After parsing, there is content in the form. Fmt. Println () fmt. Println (R.host, R.method, R.url) fmt. Println (R.form) fmt. Println (R.header) fmt. Fprint (w, "Hello world!" +r.form["name"][0])}func handle2 (w http. Responsewriter, R *http. Request) {r.parseform ()//default does not resolve, form is empty. After parsing, there is content in the form. Fmt. Println () fmt. Println (R.host, R.method, R.url) fmt. Println (R.form) fmt. Println (R.header) fmt. Fprint (W, "ppp!" +r.form["name"][0])}

6. Error handling

It is generally possible to return an error with err. If a serious problem occurs, it can be panic, and then the program ends, called a quick error. You can also capture panic with recover.

Go error handling mechanism, the official recommended err, and C almost. The combination of Panic+recover is similar to Try-catch.

Func Main () {defer func () {if err: = Recover (); Err! = nil {fmt. PRINTLN (Err)}} () Err: = Httptest. Test2 () If Err = = Nil {fmt. Println ("OK")} else {fmt. PRINTLN (Err)}}func Test2 () error {FMT. Println (one)//panic ("hehe") fmt. Println () return Nil//return FMT. Errorf ("GGG")}

7. Map and Slice

V7: = Make (map[string]int) V8: = map[string]string{"T1": "TTu", "T2": "oo",}v7["BB"] = 2xx, OK: = v7["BB"]//key whether FMT exists. Println (Len (V8), XX, OK) for k, V: = Range V7 {fmt. Println (k, v)}v9: = []string{"ddd", "RR"}fmt. Println (v9) v10: = Make ([]string, 5, ten) fmt. Println (Len (V10), Cap (V10)) Fmt. Println (V10[4])//Normal FMT. Println (V10[5])//exception

8. Make can only allocate memory for map, Slice, CHANNL, and new to all types. new Returns a pointer


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.