Golang 기반

6251 단어
토대
package main
import (
  "fmt",
  "math/rand"
  "math"
)

func main() {
  //              
  ftm.Print("My favorite time it", rand.Intn(10))
  fmt.Println(math.Pi)
}

변수 정의
//    
//rune,int8,int16,int32,int64
//byte,uint8,uint16,uint32,uint64
//rune == int32
//byte == uint8

//go         
var s string = "Hello"
s[0] = 'W' //  
//        
s := "Hello"
c := []byte(s)//   s       
c[0] = 'W'
s2 := string(c)  //      
//         ,      
var i, j = 1, 2
var x, y int = 1, 2
k := 3

var (
  ToBe  bool        = false
  MaxInt uint64     = 1 << 64 - 1
)

const f = "%T(%v)\
" const ( Big = 1 << 100 Small = Big >> 99 ) const ( x = iota //0 y = iota //1 z = iota //2 w //3 ) err = errors.New("emmit a error")

함수.
func add(x, y int) int {
  return x + y
}

func swap(x, y) (string, string) {
  return y, x
}

//   
func split(sum int) (x, y int) {
  x = sum * 4 / 9
  y = sum - x
  return
}

//       
type testInt func(int) bool  //        

순환하다
sum := 0
for i := 0 ; i < 10; i++ {
  sum += i
}

sum := 0
for ;sum < 1000; {
  sum += sum
}

sum := 0
for sum < 1000 {
  sum += sum
}

//   
for {

}

조건문
if x < 10 {
  //.....
}

if v := math.Pow(x, n); v < lim {
  //...
} else {
  //....
}

import runtime
switch os := runtime.GOOS; os {
  case "darwin":
    fmt.Println("Mac os")
  case "linux":
    fmt.Println("Linux.")
  default:
    fmt.Printf("%s", os)
}

import time
t := time.Now()
switch {
case t.Hour() < 12:
  fmt.Println("Good morning")
case t.Hour() < 17:
  fmt.Println("Good afternoon")
default:
  fmt.Println("Good evening")
}

포인터
i, j := 42, 2701
p := &i
fmt.Println(*p)
*p = 81
//golang       

구조체
type Vertex struct {
  X int
  Y int
}
//       
v := Vertex{1, 2}
v.X = 12

p = &Vertex{1, 2}
p.X = 12

v := Vertex{X: 1}

배열 및 슬라이스
var a [10]int                 //  
//[3]int [4]int      ,        
c := [...]{4, 5, 6}  //      
s := []int{2, 3, 4, 5, 6, 7} //  

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

    
game := [][]string{
        []string{"_", "_", "_"},
        []string{"_", "_", "_"},
        []string{"_", "_", "_"},
    }
game[0][0] = "X"
game[2][2] = "O"
game[2][0] = "X"
game[1][0] = "O"
game[0][2] = "X"

strings.Join(game[0], " ") //      

// slice  
s[low:hig] //    

//  slice
a := make([]int, 5) //len(a) == 5
b := make([]int, 0, 5) // len(b) = 0, cap(b) = 5
//slice 0  nil

// slice    
var a []int

a = append(a, 0) //   slice   ,    slice

var pow = []int{1, 2, 4, 8, 16, 32}
for i, v := range pow {
  
}
for _,v := range pow{

}

map
type Vertex struct {
  Lat, Long float64
}

var m map[string]Vertex
m = make(map[string]Vertex)

var m = map[string]Vertex{
    "Bell Labs": {40.68433, -74.39967},
    "Google":    {37.42202, -122.08408},
}

delete(m, "Bell Labs")

v, ok := m["Bell Labs"]


함수
func compute(fn func(float64, float64) float64) float64 {
    return fn(3, 4)
}
//    
func adder() func(int) int {
  sum := 0
  return func(x int) int {
    sum+=x
    return sum 
  }
}

//      
func fibonacci() func() int {
    a, b := 0, 1
    return func() int {
        a, b = b, a+b
        return a
    }
}

메서드
type Vertex struct {
  X,Y float64
}

func (v *Vertex) Abs() float64 {
  return  math.Sqrt(v.X * v.X + v.Y*v.Y)
}

v := &Vertex{1, 3}
s := v.Abs()

이음매
//               。
type  Abser interface {
  Abs() float
}

type Reader interface {
    Read(b []byte) (n int, err error)
}

type Writer interface {
    Write(b []byte) (n int, err error)
}

type ReadWriter interface {
    Reader
    Writer
}

//fmt               ,        ,        
type Stringer interface {
    String() string
}

Reader
package main

import (
    "fmt"
    "io"
    "strings"
)

func main() {
    r := strings.NewReader("Hello, Reader!")

    b := make([]byte, 8)
    for {
        n, err := r.Read(b)
        fmt.Printf("n = %v err = %v b = %v\
", n, err, b) fmt.Printf("b[:n] = %q\
", b[:n]) if err == io.EOF { break } } }

가장 간단한 웹 서버
package main

import (
    "fmt"
    "log"
    "net/http"
)

type Hello struct{}

func (h Hello) ServeHTTP(
    w http.ResponseWriter,
    r *http.Request) {
    fmt.Fprint(w, "Hello!")
}

func main() {
    var h Hello
    err := http.ListenAndServe("localhost:4000", h)
    if err != nil {
        log.Fatal(err)
    }
}

goroutine
package main

import (
    "fmt"
    "time"
)

func say(s string) {
    for i := 0; i < 5; i++ {
        time.Sleep(100 * time.Millisecond)
        fmt.Println(s)
    }
}

func main() {
    go say("world")
    say("hello")
}


chanel
ch := make(chan int)

ch 

서로 배척하다
package main

import (
    "fmt"
    "sync"
    "time"
)

// SafeCounter          。
type SafeCounter struct {
    v   map[string]int
    mux sync.Mutex
}

// Inc      key       。
func (c *SafeCounter) Inc(key string) {
    c.mux.Lock()
    // Lock            goroutine     c.v
    c.v[key]++
    c.mux.Unlock()
}

// Value      key         。
func (c *SafeCounter) Value(key string) int {
    c.mux.Lock()
    // Lock            goroutine     c.v
    defer c.mux.Unlock()
    return c.v[key]
}

func main() {
    c := SafeCounter{v: make(map[string]int)}
    for i := 0; i < 1000; i++ {
        go c.Inc("somekey")
    }

    time.Sleep(time.Second)
    fmt.Println(c.Value("somekey"))
}

좋은 웹페이지 즐겨찾기