Skip to content

Instantly share code, notes, and snippets.

View tomtsang's full-sized avatar

tomtsang tomtsang

  • ttechnology
  • china
View GitHub Profile
@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-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 / 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 / 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 / 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 / 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 / slice-append-slice.go
Created February 8, 2018 01:54
slice-append-slice.go
package main
import "fmt"
func main() {
sl_from := []int{1, 2, 3}
sl3 := []int{1, 2, 3}
sl3 = append(sl3, 4, 5, 6)
sl3 = append(sl3, sl_from...)
fmt.Println(sl3)
@tomtsang
tomtsang / slice-1.go
Created February 7, 2018 15:48
slice-1.go
package main
import "fmt"
func main() {
s1 := []byte{'p', 'o', 'e', 'm'} //且
s2 := s1[2:]
// s2[1] = 't' // 这个时候, s1, s2 都会改变
for i := 0; i < len(s1); i++ {
fmt.Printf("Slice at %d is %v\n", i, s1[i])
@tomtsang
tomtsang / fibonacci-use-cache.go
Created February 7, 2018 15:16
fibonacci-use-cache.go
package main
import (
"fmt"
"time"
)
const LIM = 41
var fibs [LIM]uint64
@tomtsang
tomtsang / sub-time-longCalculation.go
Created February 7, 2018 15:13
sub-time-longCalculation.go
start := time.Now()
longCalculation()
end := time.Now()
delta := end.Sub(start)
fmt.Printf("longCalculation took this amount of time: %s\n", delta)