Skip to content

Instantly share code, notes, and snippets.

View tomtsang's full-sized avatar

tomtsang tomtsang

  • ttechnology
  • china
View GitHub Profile
@tomtsang
tomtsang / slice-copy-append.go
Created February 8, 2018 01:54
slice-copy-append.go
package main
import "fmt"
func main() {
sl_from := []int{1, 2, 3}
sl_to := make([]int, 10)
n := copy(sl_to, sl_from)
fmt.Println(sl_to)
fmt.Printf("Copied %d elements\n", n) // n == 3
@tomtsang
tomtsang / count_characters.go
Created February 8, 2018 02:20
count_characters.go
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
// count number of characters:
str1 := "asSASA ddd dsjkdsjs dk"
@tomtsang
tomtsang / FindDigits.go
Created February 8, 2018 02:38
FindDigits.go
// 函数 FindDigits 将一个文件加载到内存,然后搜索其中所有的数字并返回一个切片。
var digitRegexp = regexp.MustCompile("[0-9]+")
func FindDigits(filename string) []byte {
b, _ := ioutil.ReadFile(filename)
return digitRegexp.Find(b)
}
// 这段代码可以顺利运行,但返回的 []byte 指向的底层是整个文件的数据。只要该返回的切片不被释放,垃圾回收器就不能释放整个文件所占用的内存。换句话说,一点点有用的数据却占用了整个文件的内存。
@tomtsang
tomtsang / regexp-Compile.go
Created February 8, 2018 03:17
regexp-Compile.go
package main
import (
"fmt"
"regexp"
"strconv"
)
func main() {
//目标字符串
searchIn := "John: 2578.34 William: 4567.23 Steve: 5632.18"
@tomtsang
tomtsang / struct-factory-method.go
Created February 10, 2018 03:58
struct-factory-method.go
type File struct {
fd int // 文件描述符
name string // 文件名
}
// 下面是这个结构体类型对应的工厂方法,它返回一个指向结构体实例的指针:
func NewFile(fd int, name string) *File {
if fd < 0 {
return nil
}
@tomtsang
tomtsang / struct-factory-method-new.go
Created February 10, 2018 04:01
struct-factory-method-new.go
type matrix struct {
...
}
func NewMatrix(params) *matrix {
m := new(matrix) // 初始化 m
return m
}
// 在其他包里使用工厂方法:
@tomtsang
tomtsang / struct-anonymous-method.go
Created February 10, 2018 08:07
struct-anonymous-method.go
package main
import (
"fmt"
"math"
)
type Point struct {
x, y float64
}
@tomtsang
tomtsang / golang-interface-methodset.go
Created February 11, 2018 02:27
golang-interface-methodset.go
package main
import (
"fmt"
)
type List []int
// 值的方法
func (l List) Len() int {
@tomtsang
tomtsang / path-error.go
Created February 11, 2018 14:54
path-error.go
// PathError records an error and the operation and file path that caused it.
type PathError struct {
Op string // "open", "unlink", etc.
Path string // The associated file.
Err error // Returned by the system call.
}
func (e *PathError) String() string {
return e.Op + " " + e.Path + ": "+ e.Err.Error()
}
@tomtsang
tomtsang / error-type.go
Created February 11, 2018 14:56
error-type.go
type SyntaxError struct {
msg string // description of error
// error occurred after reading Offset bytes, from which line and columnnr can be obtained
Offset int64
}
func (e *SyntaxError) String() string { return e.msg }
if serr, ok := err.(*json.SyntaxError); ok {