Code Monkey home page Code Monkey logo

example's People

Contributors

syfun avatar

Stargazers

 avatar

Watchers

 avatar  avatar

example's Issues

Golang Cgo examples

参考

cgo
Command cgo
C? Go? Cgo!
在 Go 语言中调用 C 代码
在 Go 语言中调用 C++ 代码

重要! 重要! 重要!

import "C"必须紧跟着C代码的注释

内联C代码

main.go

package main

/*
#include "stdio.h"

void hello() {
	printf("hello world!\n");
}
*/
import "C"

func main() {
	C.hello()
}

通过go run main.go的方式运行

独立C源码

test.h

void hello();

test.c

#include "stdio.h"
#include "test.h"

void hello() {
    printf("hello world!\n");
}

main.go

package main

// #include "test.h"
import "C"

func main() {
	C.hello()
}
$ go build -o cgo
$ ./cgo

Golang Enum

type ByteSize float64

const (
    _           = iota // ignore first value by assigning to blank identifier, iota = 0
    KB ByteSize = 1 << (10 * iota) // iota = 1
    MB
    GB
    TB
    PB
    EB
    ZB
    YB
)

type Color int

const (
    RED Color = 1
    BLUE Color = 2
)

Golang convert

hex string <=> byte array

package main

import (
	"encoding/hex"
	"fmt"
)

func main() {
	a := []byte(`hello`)
	b := "hello"
	c := "68656c6c6f"
	fmt.Printf("Ox%x\n", a)
	fmt.Printf("Ox%x\n", b)
	fmt.Println(hex.EncodeToString(a))
	fmt.Println(hex.DecodeString(c))
}

Result:

Ox68656c6c6f
Ox68656c6c6f
68656c6c6f
[104 101 108 108 111] <nil>

Golang Channel

select quit

package main

import (
	"fmt"
	"time"
)

func main() {
	quit := make(chan bool)
	go func() {
		for {
			select {
			case <-quit:
				fmt.Println("return")
				return
			default:
				fmt.Println(".")
				time.Sleep(time.Millisecond * 100)
			}
		}
	}()

	// Do stuff
	time.Sleep(time.Second)

	// Quit goroutine
	quit <- true
}

Golang JSON

Marshal

func Marshal(v interface{}) ([]byte, error)

调用流程

  1. 如果v实现了Marshaler接口,而且v不是nil指针,Marshal会调用v的MarshalJSON方法生成json

  2. 如果没有MarshalJSON方法,但是实现了encoding.TextMarshaler接口,那么调用MarshalText方法,最终生成一个字符串

  3. 如果都没有的话,按照默认的方式执行

Go和Json的类型对应

go type json type
boolean boolean
floating point, integer and other number number
string utf-8 string
array, slice array
[]byte base64-encoded string
nil null
struct object

"<", ">", "&" will be escaped to "\u003c", "\u003e", "\u0026", to keep some browsers from misinterpreting JSON output as HTML. This escaping can be disabled using an Encoder that had SetEscapeHTML(false) called on it.

结构体

结构体会被编码成json对象, 每一个可导出字段(exported struct field, 即首字母大写字段)都会成为对象的key, key的名称默认是字段名称(也可以通过添加json标签来修改).

type Example struct {
	Field1 string `json:"field1"`   // key是field1
	Field2 int    `json:"field2,omitempty"` // key是field2,如果为空, 那么json中就会没有这个Key
	Field3 string `json:",omitempty"`  // key是Field3, 如果为空, 那么json中就会没有这个Key
	Field4 string `json:"-"`  // 忽略
	Field5 string `json:"-,"`  // key是-
    Field6 int    `json:"field6,string"` // key是field6, 值会转成string
	Field7 string
	other  string  // 忽略
}

{"field1", "field2", "field3", "field4", "field5", 10, "field7", ""}

# Marshal to

{"field1":"field1","field2":"field2","Field3":"field3","-":"field5","field6":"10","Field7":"field7"}


{"field1", "", "", "field4", "field5", 20, "field7", ""}

# Marshal to

{"field1":"field1","-":"field5","field6":"20","Field7":"field7"}

匿名结构体

实现MarshalJSON时,如果需要对某个具体的field进行修改(比如时间转时间戳),那么可以使用如下方法。

func (example *Example) MarshalJSON() ([]byte, error) {
	type Alias Example
	return json.Marshal(struct {
		Other string
		*Alias
	}{
		example.other,
		(*Alias)(example),
	})
}

map

map的key必须是string, integer type, 或者实现了encoding.TextMarshaler。

优先级:

  1. string直接使用
  2. encoding.TextMarshaler ## 有疑问
  3. integer转成string

其他

  1. 指针 => 它所指向的值
  2. 接口 => 它所包含的具体指
  3. Channel, complex, function不能转换, 否则报错UnsupportedTypeError

源码

json

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.