From 376518d77fb5d718f90c8b66ea25660aa3734032 Mon Sep 17 00:00:00 2001 From: Joel Sing Date: Wed, 27 Jan 2021 01:48:47 +1100 Subject: runtime,syscall: convert syscall on openbsd/arm64 to libc Convert the syscall package on openbsd/arm64 to use libc rather than performing direct system calls. Updates #36435 Change-Id: I7e1da8537cea9ed9bf2676f181e56ae99383333f Reviewed-on: https://go-review.googlesource.com/c/go/+/286815 Trust: Joel Sing Reviewed-by: Cherry Zhang Run-TryBot: Cherry Zhang TryBot-Result: Go Bot --- src/runtime/sys_openbsd3.go | 2 +- src/runtime/sys_openbsd_arm64.s | 295 +++++++++++ src/syscall/asm_openbsd_arm64.s | 140 +---- src/syscall/exec_bsd.go | 2 +- src/syscall/exec_libc2.go | 2 +- src/syscall/mkall.sh | 5 +- src/syscall/syscall_openbsd1.go | 2 +- src/syscall/syscall_openbsd_libc.go | 2 +- src/syscall/zsyscall_openbsd_arm64.go | 941 +++++++++++++++++++++++++++++----- src/syscall/zsyscall_openbsd_arm64.s | 233 +++++++++ 10 files changed, 1372 insertions(+), 252 deletions(-) create mode 100644 src/syscall/zsyscall_openbsd_arm64.s diff --git a/src/runtime/sys_openbsd3.go b/src/runtime/sys_openbsd3.go index a8f9b0ee14..4d4c88e3ac 100644 --- a/src/runtime/sys_openbsd3.go +++ b/src/runtime/sys_openbsd3.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// +build openbsd,amd64 +// +build openbsd,amd64 openbsd,arm64 package runtime diff --git a/src/runtime/sys_openbsd_arm64.s b/src/runtime/sys_openbsd_arm64.s index 0fd983ef25..9b4acc90a5 100644 --- a/src/runtime/sys_openbsd_arm64.s +++ b/src/runtime/sys_openbsd_arm64.s @@ -403,3 +403,298 @@ TEXT runtime·sigaltstack_trampoline(SB),NOSPLIT,$0 MOVD $0, R0 // crash on syscall failure MOVD R0, (R0) RET + +// syscall calls a function in libc on behalf of the syscall package. +// syscall takes a pointer to a struct like: +// struct { +// fn uintptr +// a1 uintptr +// a2 uintptr +// a3 uintptr +// r1 uintptr +// r2 uintptr +// err uintptr +// } +// syscall must be called on the g0 stack with the +// C calling convention (use libcCall). +// +// syscall expects a 32-bit result and tests for 32-bit -1 +// to decide there was an error. +TEXT runtime·syscall(SB),NOSPLIT,$0 + MOVD R0, R19 // pointer to args + + MOVD (0*8)(R19), R11 // fn + MOVD (1*8)(R19), R0 // a1 + MOVD (2*8)(R19), R1 // a2 + MOVD (3*8)(R19), R2 // a3 + MOVD $0, R3 // vararg + + CALL R11 + + MOVD R0, (4*8)(R19) // r1 + MOVD R1, (5*8)(R19) // r2 + + // Standard libc functions return -1 on error + // and set errno. + CMPW $-1, R0 + BNE ok + + // Get error code from libc. + CALL libc_errno(SB) + MOVW (R0), R0 + MOVD R0, (6*8)(R19) // err + +ok: + RET + +// syscallX calls a function in libc on behalf of the syscall package. +// syscallX takes a pointer to a struct like: +// struct { +// fn uintptr +// a1 uintptr +// a2 uintptr +// a3 uintptr +// r1 uintptr +// r2 uintptr +// err uintptr +// } +// syscallX must be called on the g0 stack with the +// C calling convention (use libcCall). +// +// syscallX is like syscall but expects a 64-bit result +// and tests for 64-bit -1 to decide there was an error. +TEXT runtime·syscallX(SB),NOSPLIT,$0 + MOVD R0, R19 // pointer to args + + MOVD (0*8)(R19), R11 // fn + MOVD (1*8)(R19), R0 // a1 + MOVD (2*8)(R19), R1 // a2 + MOVD (3*8)(R19), R2 // a3 + MOVD $0, R3 // vararg + + CALL R11 + + MOVD R0, (4*8)(R19) // r1 + MOVD R1, (5*8)(R19) // r2 + + // Standard libc functions return -1 on error + // and set errno. + CMP $-1, R0 + BNE ok + + // Get error code from libc. + CALL libc_errno(SB) + MOVW (R0), R0 + MOVD R0, (6*8)(R19) // err + +ok: + RET + +// syscall6 calls a function in libc on behalf of the syscall package. +// syscall6 takes a pointer to a struct like: +// struct { +// fn uintptr +// a1 uintptr +// a2 uintptr +// a3 uintptr +// a4 uintptr +// a5 uintptr +// a6 uintptr +// r1 uintptr +// r2 uintptr +// err uintptr +// } +// syscall6 must be called on the g0 stack with the +// C calling convention (use libcCall). +// +// syscall6 expects a 32-bit result and tests for 32-bit -1 +// to decide there was an error. +TEXT runtime·syscall6(SB),NOSPLIT,$0 + MOVD R0, R19 // pointer to args + + MOVD (0*8)(R19), R11 // fn + MOVD (1*8)(R19), R0 // a1 + MOVD (2*8)(R19), R1 // a2 + MOVD (3*8)(R19), R2 // a3 + MOVD (4*8)(R19), R3 // a4 + MOVD (5*8)(R19), R4 // a5 + MOVD (6*8)(R19), R5 // a6 + MOVD $0, R6 // vararg + + CALL R11 + + MOVD R0, (7*8)(R19) // r1 + MOVD R1, (8*8)(R19) // r2 + + // Standard libc functions return -1 on error + // and set errno. + CMPW $-1, R0 + BNE ok + + // Get error code from libc. + CALL libc_errno(SB) + MOVW (R0), R0 + MOVD R0, (9*8)(R19) // err + +ok: + RET + +// syscall6X calls a function in libc on behalf of the syscall package. +// syscall6X takes a pointer to a struct like: +// struct { +// fn uintptr +// a1 uintptr +// a2 uintptr +// a3 uintptr +// a4 uintptr +// a5 uintptr +// a6 uintptr +// r1 uintptr +// r2 uintptr +// err uintptr +// } +// syscall6X must be called on the g0 stack with the +// C calling convention (use libcCall). +// +// syscall6X is like syscall6 but expects a 64-bit result +// and tests for 64-bit -1 to decide there was an error. +TEXT runtime·syscall6X(SB),NOSPLIT,$0 + MOVD R0, R19 // pointer to args + + MOVD (0*8)(R19), R11 // fn + MOVD (1*8)(R19), R0 // a1 + MOVD (2*8)(R19), R1 // a2 + MOVD (3*8)(R19), R2 // a3 + MOVD (4*8)(R19), R3 // a4 + MOVD (5*8)(R19), R4 // a5 + MOVD (6*8)(R19), R5 // a6 + MOVD $0, R6 // vararg + + CALL R11 + + MOVD R0, (7*8)(R19) // r1 + MOVD R1, (8*8)(R19) // r2 + + // Standard libc functions return -1 on error + // and set errno. + CMP $-1, R0 + BNE ok + + // Get error code from libc. + CALL libc_errno(SB) + MOVW (R0), R0 + MOVD R0, (9*8)(R19) // err + +ok: + RET + +// syscall10 calls a function in libc on behalf of the syscall package. +// syscall10 takes a pointer to a struct like: +// struct { +// fn uintptr +// a1 uintptr +// a2 uintptr +// a3 uintptr +// a4 uintptr +// a5 uintptr +// a6 uintptr +// a7 uintptr +// a8 uintptr +// a9 uintptr +// a10 uintptr +// r1 uintptr +// r2 uintptr +// err uintptr +// } +// syscall10 must be called on the g0 stack with the +// C calling convention (use libcCall). +TEXT runtime·syscall10(SB),NOSPLIT,$0 + MOVD R0, R19 // pointer to args + + MOVD (0*8)(R19), R11 // fn + MOVD (1*8)(R19), R0 // a1 + MOVD (2*8)(R19), R1 // a2 + MOVD (3*8)(R19), R2 // a3 + MOVD (4*8)(R19), R3 // a4 + MOVD (5*8)(R19), R4 // a5 + MOVD (6*8)(R19), R5 // a6 + MOVD (7*8)(R19), R6 // a7 + MOVD (8*8)(R19), R7 // a8 + MOVD (9*8)(R19), R8 // a9 + MOVD (10*8)(R19), R9 // a10 + MOVD $0, R10 // vararg + + CALL R11 + + MOVD R0, (11*8)(R19) // r1 + MOVD R1, (12*8)(R19) // r2 + + // Standard libc functions return -1 on error + // and set errno. + CMPW $-1, R0 + BNE ok + + // Get error code from libc. + CALL libc_errno(SB) + MOVW (R0), R0 + MOVD R0, (13*8)(R19) // err + +ok: + RET + +// syscall10X calls a function in libc on behalf of the syscall package. +// syscall10X takes a pointer to a struct like: +// struct { +// fn uintptr +// a1 uintptr +// a2 uintptr +// a3 uintptr +// a4 uintptr +// a5 uintptr +// a6 uintptr +// a7 uintptr +// a8 uintptr +// a9 uintptr +// a10 uintptr +// r1 uintptr +// r2 uintptr +// err uintptr +// } +// syscall10X must be called on the g0 stack with the +// C calling convention (use libcCall). +// +// syscall10X is like syscall10 but expects a 64-bit result +// and tests for 64-bit -1 to decide there was an error. +TEXT runtime·syscall10X(SB),NOSPLIT,$0 + MOVD R0, R19 // pointer to args + + MOVD (0*8)(R19), R11 // fn + MOVD (1*8)(R19), R0 // a1 + MOVD (2*8)(R19), R1 // a2 + MOVD (3*8)(R19), R2 // a3 + MOVD (4*8)(R19), R3 // a4 + MOVD (5*8)(R19), R4 // a5 + MOVD (6*8)(R19), R5 // a6 + MOVD (7*8)(R19), R6 // a7 + MOVD (8*8)(R19), R7 // a8 + MOVD (9*8)(R19), R8 // a9 + MOVD (10*8)(R19), R9 // a10 + MOVD $0, R10 // vararg + + CALL R11 + + MOVD R0, (11*8)(R19) // r1 + MOVD R1, (12*8)(R19) // r2 + + // Standard libc functions return -1 on error + // and set errno. + CMP $-1, R0 + BNE ok + + // Get error code from libc. + CALL libc_errno(SB) + MOVW (R0), R0 + MOVD R0, (13*8)(R19) // err + +ok: + RET diff --git a/src/syscall/asm_openbsd_arm64.s b/src/syscall/asm_openbsd_arm64.s index dcbed10cbe..61595a11a3 100644 --- a/src/syscall/asm_openbsd_arm64.s +++ b/src/syscall/asm_openbsd_arm64.s @@ -4,127 +4,29 @@ #include "textflag.h" -// See comment in runtime/sys_openbsd_arm64.s re this construction. -#define INVOKE_SYSCALL \ - SVC; \ - NOOP; \ - NOOP +// +// System call support for ARM64, OpenBSD +// -// func Syscall(trap int64, a1, a2, a3 int64) (r1, r2, err int64); -TEXT ·Syscall(SB),NOSPLIT,$0-56 - BL runtime·entersyscall(SB) - MOVD a1+8(FP), R0 - MOVD a2+16(FP), R1 - MOVD a3+24(FP), R2 - MOVD $0, R3 - MOVD $0, R4 - MOVD $0, R5 - MOVD trap+0(FP), R8 // syscall number - INVOKE_SYSCALL - BCC ok - MOVD $-1, R4 - MOVD R4, r1+32(FP) // r1 - MOVD ZR, r2+40(FP) // r2 - MOVD R0, err+48(FP) // errno - BL runtime·exitsyscall(SB) - RET -ok: - MOVD R0, r1+32(FP) // r1 - MOVD R1, r2+40(FP) // r2 - MOVD ZR, err+48(FP) // errno - BL runtime·exitsyscall(SB) - RET +// Provide these function names via assembly so they are provided as ABI0, +// rather than ABIInternal. -TEXT ·Syscall6(SB),NOSPLIT,$0-80 - BL runtime·entersyscall(SB) - MOVD a1+8(FP), R0 - MOVD a2+16(FP), R1 - MOVD a3+24(FP), R2 - MOVD a4+32(FP), R3 - MOVD a5+40(FP), R4 - MOVD a6+48(FP), R5 - MOVD trap+0(FP), R8 // syscall number - INVOKE_SYSCALL - BCC ok - MOVD $-1, R4 - MOVD R4, r1+56(FP) // r1 - MOVD ZR, r2+64(FP) // r2 - MOVD R0, err+72(FP) // errno - BL runtime·exitsyscall(SB) - RET -ok: - MOVD R0, r1+56(FP) // r1 - MOVD R1, r2+64(FP) // r2 - MOVD ZR, err+72(FP) // errno - BL runtime·exitsyscall(SB) - RET +// func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno) +TEXT ·Syscall(SB),NOSPLIT,$0-56 + JMP ·syscallInternal(SB) -TEXT ·Syscall9(SB),NOSPLIT,$0-104 - BL runtime·entersyscall(SB) - MOVD a1+8(FP), R0 - MOVD a2+16(FP), R1 - MOVD a3+24(FP), R2 - MOVD a4+32(FP), R3 - MOVD a5+40(FP), R4 - MOVD a6+48(FP), R5 - MOVD a7+56(FP), R6 - MOVD a8+64(FP), R7 - MOVD a9+72(FP), R8 // on stack - MOVD R8, 8(RSP) - MOVD num+0(FP), R8 // syscall number - INVOKE_SYSCALL - BCC ok - MOVD $-1, R4 - MOVD R4, r1+80(FP) // r1 - MOVD ZR, r2+88(FP) // r2 - MOVD R0, err+96(FP) // errno - BL runtime·exitsyscall(SB) - RET -ok: - MOVD R0, r1+80(FP) // r1 - MOVD R1, r2+88(FP) // r2 - MOVD ZR, err+96(FP) // errno - BL runtime·exitsyscall(SB) - RET +// func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno) +TEXT ·Syscall6(SB),NOSPLIT,$0-80 + JMP ·syscall6Internal(SB) -TEXT ·RawSyscall(SB),NOSPLIT,$0-56 - MOVD a1+8(FP), R0 - MOVD a2+16(FP), R1 - MOVD a3+24(FP), R2 - MOVD $0, R3 - MOVD $0, R4 - MOVD $0, R5 - MOVD trap+0(FP), R8 // syscall number - INVOKE_SYSCALL - BCC ok - MOVD $-1, R4 - MOVD R4, r1+32(FP) // r1 - MOVD ZR, r2+40(FP) // r2 - MOVD R0, err+48(FP) // errno - RET -ok: - MOVD R0, r1+32(FP) // r1 - MOVD R1, r2+40(FP) // r2 - MOVD ZR, err+48(FP) // errno - RET +// func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno) +TEXT ·RawSyscall(SB),NOSPLIT,$0-56 + JMP ·rawSyscallInternal(SB) -TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 - MOVD a1+8(FP), R0 - MOVD a2+16(FP), R1 - MOVD a3+24(FP), R2 - MOVD a4+32(FP), R3 - MOVD a5+40(FP), R4 - MOVD a6+48(FP), R5 - MOVD trap+0(FP), R8 // syscall number - INVOKE_SYSCALL - BCC ok - MOVD $-1, R4 - MOVD R4, r1+56(FP) // r1 - MOVD ZR, r2+64(FP) // r2 - MOVD R0, err+72(FP) // errno - RET -ok: - MOVD R0, r1+56(FP) // r1 - MOVD R1, r2+64(FP) // r2 - MOVD ZR, err+72(FP) // errno - RET +// func RawSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno) +TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 + JMP ·rawSyscall6Internal(SB) + +// func Syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err Errno) +TEXT ·Syscall9(SB),NOSPLIT,$0-104 + JMP ·syscall9Internal(SB) diff --git a/src/syscall/exec_bsd.go b/src/syscall/exec_bsd.go index 9069ef4613..940a81b58e 100644 --- a/src/syscall/exec_bsd.go +++ b/src/syscall/exec_bsd.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// +build dragonfly freebsd netbsd openbsd,!amd64 +// +build dragonfly freebsd netbsd openbsd,!amd64,!arm64 package syscall diff --git a/src/syscall/exec_libc2.go b/src/syscall/exec_libc2.go index 496e7cf4c3..45d3f85baf 100644 --- a/src/syscall/exec_libc2.go +++ b/src/syscall/exec_libc2.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// +build darwin openbsd,amd64 +// +build darwin openbsd,amd64 openbsd,arm64 package syscall diff --git a/src/syscall/mkall.sh b/src/syscall/mkall.sh index 87e5157416..d1e28efa8c 100755 --- a/src/syscall/mkall.sh +++ b/src/syscall/mkall.sh @@ -313,15 +313,16 @@ openbsd_arm) mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" ;; openbsd_arm64) - GOOSARCH_in="syscall_openbsd1.go syscall_openbsd_$GOARCH.go" + GOOSARCH_in="syscall_openbsd_libc.go syscall_openbsd_$GOARCH.go" mkerrors="$mkerrors -m64" - mksyscall="./mksyscall.pl -openbsd" + mksyscall="./mksyscall.pl -openbsd -libc" mksysctl="./mksysctl_openbsd.pl" zsysctl="zsysctl_openbsd.go" mksysnum="curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl" # Let the type of C char be signed to make the bare syscall # API consistent between platforms. mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" + mkasm="go run mkasm.go" ;; openbsd_mips64) GOOSARCH_in="syscall_openbsd1.go syscall_openbsd_$GOARCH.go" diff --git a/src/syscall/syscall_openbsd1.go b/src/syscall/syscall_openbsd1.go index d8065374fb..2c7d0f8c90 100644 --- a/src/syscall/syscall_openbsd1.go +++ b/src/syscall/syscall_openbsd1.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// +build openbsd,!amd64 +// +build openbsd,!amd64,!arm64 package syscall diff --git a/src/syscall/syscall_openbsd_libc.go b/src/syscall/syscall_openbsd_libc.go index 191c7e0e43..2fcc2011bc 100644 --- a/src/syscall/syscall_openbsd_libc.go +++ b/src/syscall/syscall_openbsd_libc.go @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// +build openbsd,amd64 +// +build openbsd,amd64 openbsd,arm64 package syscall diff --git a/src/syscall/zsyscall_openbsd_arm64.go b/src/syscall/zsyscall_openbsd_arm64.go index 626ce17703..90a46f3c4b 100644 --- a/src/syscall/zsyscall_openbsd_arm64.go +++ b/src/syscall/zsyscall_openbsd_arm64.go @@ -1,4 +1,4 @@ -// mksyscall.pl -openbsd -tags openbsd,arm64 syscall_bsd.go syscall_openbsd.go syscall_openbsd_arm64.go +// mksyscall.pl -openbsd -libc -tags openbsd,arm64 syscall_bsd.go syscall_openbsd.go syscall_openbsd_libc.go syscall_openbsd_arm64.go // Code generated by the command above; DO NOT EDIT. // +build openbsd,arm64 @@ -10,7 +10,7 @@ import "unsafe" // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(ngid int, gid *_Gid_t) (n int, err error) { - r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + r0, _, e1 := rawSyscall(funcPC(libc_getgroups_trampoline), uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -18,20 +18,30 @@ func getgroups(ngid int, gid *_Gid_t) (n int, err error) { return } +func libc_getgroups_trampoline() + +//go:linkname libc_getgroups libc_getgroups +//go:cgo_import_dynamic libc_getgroups getgroups "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(ngid int, gid *_Gid_t) (err error) { - _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) + _, _, e1 := rawSyscall(funcPC(libc_setgroups_trampoline), uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_setgroups_trampoline() + +//go:linkname libc_setgroups libc_setgroups +//go:cgo_import_dynamic libc_setgroups setgroups "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { - r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) + r0, _, e1 := syscall6(funcPC(libc_wait4_trampoline), uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -39,10 +49,15 @@ func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err return } +func libc_wait4_trampoline() + +//go:linkname libc_wait4 libc_wait4 +//go:cgo_import_dynamic libc_wait4 wait4 "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { - r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + r0, _, e1 := syscall(funcPC(libc_accept_trampoline), uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -50,30 +65,45 @@ func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { return } +func libc_accept_trampoline() + +//go:linkname libc_accept libc_accept +//go:cgo_import_dynamic libc_accept accept "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) + _, _, e1 := syscall(funcPC(libc_bind_trampoline), uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } +func libc_bind_trampoline() + +//go:linkname libc_bind libc_bind +//go:cgo_import_dynamic libc_bind bind "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { - _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) + _, _, e1 := syscall(funcPC(libc_connect_trampoline), uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } +func libc_connect_trampoline() + +//go:linkname libc_connect libc_connect +//go:cgo_import_dynamic libc_connect connect "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { - r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) + r0, _, e1 := rawSyscall(funcPC(libc_socket_trampoline), uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -81,66 +111,101 @@ func socket(domain int, typ int, proto int) (fd int, err error) { return } +func libc_socket_trampoline() + +//go:linkname libc_socket libc_socket +//go:cgo_import_dynamic libc_socket socket "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { - _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) + _, _, e1 := syscall6(funcPC(libc_getsockopt_trampoline), uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_getsockopt_trampoline() + +//go:linkname libc_getsockopt libc_getsockopt +//go:cgo_import_dynamic libc_getsockopt getsockopt "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { - _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) + _, _, e1 := syscall6(funcPC(libc_setsockopt_trampoline), uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_setsockopt_trampoline() + +//go:linkname libc_setsockopt libc_setsockopt +//go:cgo_import_dynamic libc_setsockopt setsockopt "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + _, _, e1 := rawSyscall(funcPC(libc_getpeername_trampoline), uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } +func libc_getpeername_trampoline() + +//go:linkname libc_getpeername libc_getpeername +//go:cgo_import_dynamic libc_getpeername getpeername "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { - _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) + _, _, e1 := rawSyscall(funcPC(libc_getsockname_trampoline), uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } +func libc_getsockname_trampoline() + +//go:linkname libc_getsockname libc_getsockname +//go:cgo_import_dynamic libc_getsockname getsockname "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Shutdown(s int, how int) (err error) { - _, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0) + _, _, e1 := syscall(funcPC(libc_shutdown_trampoline), uintptr(s), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_shutdown_trampoline() + +//go:linkname libc_shutdown libc_shutdown +//go:cgo_import_dynamic libc_shutdown shutdown "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { - _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) + _, _, e1 := rawSyscall6(funcPC(libc_socketpair_trampoline), uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_socketpair_trampoline() + +//go:linkname libc_socketpair libc_socketpair +//go:cgo_import_dynamic libc_socketpair socketpair "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { @@ -150,7 +215,7 @@ func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Sockl } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) + r0, _, e1 := syscall6(funcPC(libc_recvfrom_trampoline), uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -158,6 +223,11 @@ func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Sockl return } +func libc_recvfrom_trampoline() + +//go:linkname libc_recvfrom libc_recvfrom +//go:cgo_import_dynamic libc_recvfrom recvfrom "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { @@ -167,17 +237,22 @@ func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) ( } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) + _, _, e1 := syscall6(funcPC(libc_sendto_trampoline), uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } +func libc_sendto_trampoline() + +//go:linkname libc_sendto libc_sendto +//go:cgo_import_dynamic libc_sendto sendto "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + r0, _, e1 := syscall(funcPC(libc_recvmsg_trampoline), uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -185,10 +260,15 @@ func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { return } +func libc_recvmsg_trampoline() + +//go:linkname libc_recvmsg libc_recvmsg +//go:cgo_import_dynamic libc_recvmsg recvmsg "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { - r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) + r0, _, e1 := syscall(funcPC(libc_sendmsg_trampoline), uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -196,10 +276,15 @@ func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { return } +func libc_sendmsg_trampoline() + +//go:linkname libc_sendmsg libc_sendmsg +//go:cgo_import_dynamic libc_sendmsg sendmsg "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) { - r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) + r0, _, e1 := syscall6(funcPC(libc_kevent_trampoline), uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout))) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -207,6 +292,11 @@ func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, ne return } +func libc_kevent_trampoline() + +//go:linkname libc_kevent libc_kevent +//go:cgo_import_dynamic libc_kevent kevent "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, timeval *[2]Timeval) (err error) { @@ -215,27 +305,37 @@ func utimes(path string, timeval *[2]Timeval) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) + _, _, e1 := syscall(funcPC(libc_utimes_trampoline), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_utimes_trampoline() + +//go:linkname libc_utimes libc_utimes +//go:cgo_import_dynamic libc_utimes utimes "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimes(fd int, timeval *[2]Timeval) (err error) { - _, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) + _, _, e1 := syscall(funcPC(libc_futimes_trampoline), uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_futimes_trampoline() + +//go:linkname libc_futimes libc_futimes +//go:cgo_import_dynamic libc_futimes futimes "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) + r0, _, e1 := syscall(funcPC(libc_fcntl_trampoline), uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -243,20 +343,30 @@ func fcntl(fd int, cmd int, arg int) (val int, err error) { return } +func libc_fcntl_trampoline() + +//go:linkname libc_fcntl libc_fcntl +//go:cgo_import_dynamic libc_fcntl fcntl "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe2(p *[2]_C_int, flags int) (err error) { - _, _, e1 := RawSyscall(SYS_PIPE2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0) + _, _, e1 := rawSyscall(funcPC(libc_pipe2_trampoline), uintptr(unsafe.Pointer(p)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_pipe2_trampoline() + +//go:linkname libc_pipe2 libc_pipe2 +//go:cgo_import_dynamic libc_pipe2 pipe2 "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error) { - r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) + r0, _, e1 := syscall6(funcPC(libc_accept4_trampoline), uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) nfd = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -264,6 +374,11 @@ func accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int return } +func libc_accept4_trampoline() + +//go:linkname libc_accept4 libc_accept4 +//go:cgo_import_dynamic libc_accept4 accept4 "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getdents(fd int, buf []byte) (n int, err error) { @@ -273,7 +388,7 @@ func getdents(fd int, buf []byte) (n int, err error) { } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf))) + r0, _, e1 := syscall(funcPC(libc_getdents_trampoline), uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -281,6 +396,11 @@ func getdents(fd int, buf []byte) (n int, err error) { return } +func libc_getdents_trampoline() + +//go:linkname libc_getdents libc_getdents +//go:cgo_import_dynamic libc_getdents getdents "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Access(path string, mode uint32) (err error) { @@ -289,23 +409,33 @@ func Access(path string, mode uint32) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + _, _, e1 := syscall(funcPC(libc_access_trampoline), uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_access_trampoline() + +//go:linkname libc_access libc_access +//go:cgo_import_dynamic libc_access access "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { - _, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) + _, _, e1 := syscall(funcPC(libc_adjtime_trampoline), uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_adjtime_trampoline() + +//go:linkname libc_adjtime libc_adjtime +//go:cgo_import_dynamic libc_adjtime adjtime "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { @@ -314,13 +444,18 @@ func Chdir(path string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + _, _, e1 := syscall(funcPC(libc_chdir_trampoline), uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_chdir_trampoline() + +//go:linkname libc_chdir libc_chdir +//go:cgo_import_dynamic libc_chdir chdir "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chflags(path string, flags int) (err error) { @@ -329,13 +464,18 @@ func Chflags(path string, flags int) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + _, _, e1 := syscall(funcPC(libc_chflags_trampoline), uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_chflags_trampoline() + +//go:linkname libc_chflags libc_chflags +//go:cgo_import_dynamic libc_chflags chflags "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chmod(path string, mode uint32) (err error) { @@ -344,13 +484,18 @@ func Chmod(path string, mode uint32) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + _, _, e1 := syscall(funcPC(libc_chmod_trampoline), uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_chmod_trampoline() + +//go:linkname libc_chmod libc_chmod +//go:cgo_import_dynamic libc_chmod chmod "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chown(path string, uid int, gid int) (err error) { @@ -359,13 +504,18 @@ func Chown(path string, uid int, gid int) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + _, _, e1 := syscall(funcPC(libc_chown_trampoline), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } +func libc_chown_trampoline() + +//go:linkname libc_chown libc_chown +//go:cgo_import_dynamic libc_chown chown "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { @@ -374,27 +524,37 @@ func Chroot(path string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) + _, _, e1 := syscall(funcPC(libc_chroot_trampoline), uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_chroot_trampoline() + +//go:linkname libc_chroot libc_chroot +//go:cgo_import_dynamic libc_chroot chroot "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { - _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) + _, _, e1 := syscall(funcPC(libc_close_trampoline), uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_close_trampoline() + +//go:linkname libc_close libc_close +//go:cgo_import_dynamic libc_close close "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(fd int) (nfd int, err error) { - r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0) + r0, _, e1 := syscall(funcPC(libc_dup_trampoline), uintptr(fd), 0, 0) nfd = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -402,70 +562,105 @@ func Dup(fd int) (nfd int, err error) { return } +func libc_dup_trampoline() + +//go:linkname libc_dup libc_dup +//go:cgo_import_dynamic libc_dup dup "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(from int, to int) (err error) { - _, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0) + _, _, e1 := syscall(funcPC(libc_dup2_trampoline), uintptr(from), uintptr(to), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_dup2_trampoline() + +//go:linkname libc_dup2 libc_dup2 +//go:cgo_import_dynamic libc_dup2 dup2 "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { - _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) + _, _, e1 := syscall(funcPC(libc_fchdir_trampoline), uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_fchdir_trampoline() + +//go:linkname libc_fchdir libc_fchdir +//go:cgo_import_dynamic libc_fchdir fchdir "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchflags(fd int, flags int) (err error) { - _, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0) + _, _, e1 := syscall(funcPC(libc_fchflags_trampoline), uintptr(fd), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_fchflags_trampoline() + +//go:linkname libc_fchflags libc_fchflags +//go:cgo_import_dynamic libc_fchflags fchflags "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { - _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) + _, _, e1 := syscall(funcPC(libc_fchmod_trampoline), uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_fchmod_trampoline() + +//go:linkname libc_fchmod libc_fchmod +//go:cgo_import_dynamic libc_fchmod fchmod "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchown(fd int, uid int, gid int) (err error) { - _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) + _, _, e1 := syscall(funcPC(libc_fchown_trampoline), uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } +func libc_fchown_trampoline() + +//go:linkname libc_fchown libc_fchown +//go:cgo_import_dynamic libc_fchown fchown "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { - _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) + _, _, e1 := syscall(funcPC(libc_flock_trampoline), uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_flock_trampoline() + +//go:linkname libc_flock libc_flock +//go:cgo_import_dynamic libc_flock flock "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fpathconf(fd int, name int) (val int, err error) { - r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0) + r0, _, e1 := syscall(funcPC(libc_fpathconf_trampoline), uintptr(fd), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -473,74 +668,114 @@ func Fpathconf(fd int, name int) (val int, err error) { return } +func libc_fpathconf_trampoline() + +//go:linkname libc_fpathconf libc_fpathconf +//go:cgo_import_dynamic libc_fpathconf fpathconf "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, stat *Stat_t) (err error) { - _, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + _, _, e1 := syscall(funcPC(libc_fstat_trampoline), uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_fstat_trampoline() + +//go:linkname libc_fstat libc_fstat +//go:cgo_import_dynamic libc_fstat fstat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstatfs(fd int, stat *Statfs_t) (err error) { - _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) + _, _, e1 := syscall(funcPC(libc_fstatfs_trampoline), uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_fstatfs_trampoline() + +//go:linkname libc_fstatfs libc_fstatfs +//go:cgo_import_dynamic libc_fstatfs fstatfs "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { - _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) + _, _, e1 := syscall(funcPC(libc_fsync_trampoline), uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_fsync_trampoline() + +//go:linkname libc_fsync libc_fsync +//go:cgo_import_dynamic libc_fsync fsync "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ftruncate(fd int, length int64) (err error) { - _, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length)) + _, _, e1 := syscall(funcPC(libc_ftruncate_trampoline), uintptr(fd), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_ftruncate_trampoline() + +//go:linkname libc_ftruncate libc_ftruncate +//go:cgo_import_dynamic libc_ftruncate ftruncate "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) + r0, _, _ := rawSyscall(funcPC(libc_getegid_trampoline), 0, 0, 0) egid = int(r0) return } +func libc_getegid_trampoline() + +//go:linkname libc_getegid libc_getegid +//go:cgo_import_dynamic libc_getegid getegid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) + r0, _, _ := rawSyscall(funcPC(libc_geteuid_trampoline), 0, 0, 0) uid = int(r0) return } +func libc_geteuid_trampoline() + +//go:linkname libc_geteuid libc_geteuid +//go:cgo_import_dynamic libc_geteuid geteuid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) + r0, _, _ := rawSyscall(funcPC(libc_getgid_trampoline), 0, 0, 0) gid = int(r0) return } +func libc_getgid_trampoline() + +//go:linkname libc_getgid libc_getgid +//go:cgo_import_dynamic libc_getgid getgid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) + r0, _, e1 := rawSyscall(funcPC(libc_getpgid_trampoline), uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -548,34 +783,54 @@ func Getpgid(pid int) (pgid int, err error) { return } +func libc_getpgid_trampoline() + +//go:linkname libc_getpgid libc_getpgid +//go:cgo_import_dynamic libc_getpgid getpgid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgrp() (pgrp int) { - r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0) + r0, _, _ := rawSyscall(funcPC(libc_getpgrp_trampoline), 0, 0, 0) pgrp = int(r0) return } +func libc_getpgrp_trampoline() + +//go:linkname libc_getpgrp libc_getpgrp +//go:cgo_import_dynamic libc_getpgrp getpgrp "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) + r0, _, _ := rawSyscall(funcPC(libc_getpid_trampoline), 0, 0, 0) pid = int(r0) return } +func libc_getpid_trampoline() + +//go:linkname libc_getpid libc_getpid +//go:cgo_import_dynamic libc_getpid getpid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) + r0, _, _ := rawSyscall(funcPC(libc_getppid_trampoline), 0, 0, 0) ppid = int(r0) return } +func libc_getppid_trampoline() + +//go:linkname libc_getppid libc_getppid +//go:cgo_import_dynamic libc_getppid getppid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { - r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) + r0, _, e1 := syscall(funcPC(libc_getpriority_trampoline), uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -583,30 +838,45 @@ func Getpriority(which int, who int) (prio int, err error) { return } +func libc_getpriority_trampoline() + +//go:linkname libc_getpriority libc_getpriority +//go:cgo_import_dynamic libc_getpriority getpriority "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrlimit(which int, lim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) + _, _, e1 := rawSyscall(funcPC(libc_getrlimit_trampoline), uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_getrlimit_trampoline() + +//go:linkname libc_getrlimit libc_getrlimit +//go:cgo_import_dynamic libc_getrlimit getrlimit "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { - _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) + _, _, e1 := rawSyscall(funcPC(libc_getrusage_trampoline), uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_getrusage_trampoline() + +//go:linkname libc_getrusage libc_getrusage +//go:cgo_import_dynamic libc_getrusage getrusage "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getsid(pid int) (sid int, err error) { - r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0) + r0, _, e1 := rawSyscall(funcPC(libc_getsid_trampoline), uintptr(pid), 0, 0) sid = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -614,46 +884,71 @@ func Getsid(pid int) (sid int, err error) { return } +func libc_getsid_trampoline() + +//go:linkname libc_getsid libc_getsid +//go:cgo_import_dynamic libc_getsid getsid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettimeofday(tv *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) + _, _, e1 := rawSyscall(funcPC(libc_gettimeofday_trampoline), uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_gettimeofday_trampoline() + +//go:linkname libc_gettimeofday libc_gettimeofday +//go:cgo_import_dynamic libc_gettimeofday gettimeofday "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) + r0, _, _ := rawSyscall(funcPC(libc_getuid_trampoline), 0, 0, 0) uid = int(r0) return } +func libc_getuid_trampoline() + +//go:linkname libc_getuid libc_getuid +//go:cgo_import_dynamic libc_getuid getuid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Issetugid() (tainted bool) { - r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0) + r0, _, _ := syscall(funcPC(libc_issetugid_trampoline), 0, 0, 0) tainted = bool(r0 != 0) return } +func libc_issetugid_trampoline() + +//go:linkname libc_issetugid libc_issetugid +//go:cgo_import_dynamic libc_issetugid issetugid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, signum Signal) (err error) { - _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0) + _, _, e1 := syscall(funcPC(libc_kill_trampoline), uintptr(pid), uintptr(signum), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_kill_trampoline() + +//go:linkname libc_kill libc_kill +//go:cgo_import_dynamic libc_kill kill "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kqueue() (fd int, err error) { - r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0) + r0, _, e1 := syscall(funcPC(libc_kqueue_trampoline), 0, 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -661,6 +956,11 @@ func Kqueue() (fd int, err error) { return } +func libc_kqueue_trampoline() + +//go:linkname libc_kqueue libc_kqueue +//go:cgo_import_dynamic libc_kqueue kqueue "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lchown(path string, uid int, gid int) (err error) { @@ -669,13 +969,18 @@ func Lchown(path string, uid int, gid int) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) + _, _, e1 := syscall(funcPC(libc_lchown_trampoline), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid)) if e1 != 0 { err = errnoErr(e1) } return } +func libc_lchown_trampoline() + +//go:linkname libc_lchown libc_lchown +//go:cgo_import_dynamic libc_lchown lchown "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Link(path string, link string) (err error) { @@ -689,23 +994,33 @@ func Link(path string, link string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + _, _, e1 := syscall(funcPC(libc_link_trampoline), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_link_trampoline() + +//go:linkname libc_link libc_link +//go:cgo_import_dynamic libc_link link "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, backlog int) (err error) { - _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0) + _, _, e1 := syscall(funcPC(libc_listen_trampoline), uintptr(s), uintptr(backlog), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_listen_trampoline() + +//go:linkname libc_listen libc_listen +//go:cgo_import_dynamic libc_listen listen "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { @@ -714,13 +1029,18 @@ func Lstat(path string, stat *Stat_t) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + _, _, e1 := syscall(funcPC(libc_lstat_trampoline), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_lstat_trampoline() + +//go:linkname libc_lstat libc_lstat +//go:cgo_import_dynamic libc_lstat lstat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdir(path string, mode uint32) (err error) { @@ -729,13 +1049,18 @@ func Mkdir(path string, mode uint32) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + _, _, e1 := syscall(funcPC(libc_mkdir_trampoline), uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_mkdir_trampoline() + +//go:linkname libc_mkdir libc_mkdir +//go:cgo_import_dynamic libc_mkdir mkdir "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkfifo(path string, mode uint32) (err error) { @@ -744,13 +1069,18 @@ func Mkfifo(path string, mode uint32) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) + _, _, e1 := syscall(funcPC(libc_mkfifo_trampoline), uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_mkfifo_trampoline() + +//go:linkname libc_mkfifo libc_mkfifo +//go:cgo_import_dynamic libc_mkfifo mkfifo "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknod(path string, mode uint32, dev int) (err error) { @@ -759,23 +1089,33 @@ func Mknod(path string, mode uint32, dev int) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) + _, _, e1 := syscall(funcPC(libc_mknod_trampoline), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev)) if e1 != 0 { err = errnoErr(e1) } return } +func libc_mknod_trampoline() + +//go:linkname libc_mknod libc_mknod +//go:cgo_import_dynamic libc_mknod mknod "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { - _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) + _, _, e1 := syscall(funcPC(libc_nanosleep_trampoline), uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_nanosleep_trampoline() + +//go:linkname libc_nanosleep libc_nanosleep +//go:cgo_import_dynamic libc_nanosleep nanosleep "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Open(path string, mode int, perm uint32) (fd int, err error) { @@ -784,7 +1124,7 @@ func Open(path string, mode int, perm uint32) (fd int, err error) { if err != nil { return } - r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) + r0, _, e1 := syscall(funcPC(libc_open_trampoline), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -792,6 +1132,11 @@ func Open(path string, mode int, perm uint32) (fd int, err error) { return } +func libc_open_trampoline() + +//go:linkname libc_open libc_open +//go:cgo_import_dynamic libc_open open "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pathconf(path string, name int) (val int, err error) { @@ -800,7 +1145,7 @@ func Pathconf(path string, name int) (val int, err error) { if err != nil { return } - r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) + r0, _, e1 := syscall(funcPC(libc_pathconf_trampoline), uintptr(unsafe.Pointer(_p0)), uintptr(name), 0) val = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -808,6 +1153,11 @@ func Pathconf(path string, name int) (val int, err error) { return } +func libc_pathconf_trampoline() + +//go:linkname libc_pathconf libc_pathconf +//go:cgo_import_dynamic libc_pathconf pathconf "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pread(fd int, p []byte, offset int64) (n int, err error) { @@ -817,7 +1167,7 @@ func Pread(fd int, p []byte, offset int64) (n int, err error) { } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), 0) + r0, _, e1 := syscall6(funcPC(libc_pread_trampoline), uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -825,6 +1175,11 @@ func Pread(fd int, p []byte, offset int64) (n int, err error) { return } +func libc_pread_trampoline() + +//go:linkname libc_pread libc_pread +//go:cgo_import_dynamic libc_pread pread "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Pwrite(fd int, p []byte, offset int64) (n int, err error) { @@ -834,7 +1189,7 @@ func Pwrite(fd int, p []byte, offset int64) (n int, err error) { } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), 0) + r0, _, e1 := syscall6(funcPC(libc_pwrite_trampoline), uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -842,6 +1197,11 @@ func Pwrite(fd int, p []byte, offset int64) (n int, err error) { return } +func libc_pwrite_trampoline() + +//go:linkname libc_pwrite libc_pwrite +//go:cgo_import_dynamic libc_pwrite pwrite "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { @@ -851,7 +1211,7 @@ func read(fd int, p []byte) (n int, err error) { } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) + r0, _, e1 := syscall(funcPC(libc_read_trampoline), uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -859,6 +1219,11 @@ func read(fd int, p []byte) (n int, err error) { return } +func libc_read_trampoline() + +//go:linkname libc_read libc_read +//go:cgo_import_dynamic libc_read read "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Readlink(path string, buf []byte) (n int, err error) { @@ -873,7 +1238,7 @@ func Readlink(path string, buf []byte) (n int, err error) { } else { _p1 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) + r0, _, e1 := syscall(funcPC(libc_readlink_trampoline), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -881,6 +1246,11 @@ func Readlink(path string, buf []byte) (n int, err error) { return } +func libc_readlink_trampoline() + +//go:linkname libc_readlink libc_readlink +//go:cgo_import_dynamic libc_readlink readlink "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rename(from string, to string) (err error) { @@ -894,13 +1264,18 @@ func Rename(from string, to string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + _, _, e1 := syscall(funcPC(libc_rename_trampoline), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_rename_trampoline() + +//go:linkname libc_rename libc_rename +//go:cgo_import_dynamic libc_rename rename "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Revoke(path string) (err error) { @@ -909,13 +1284,18 @@ func Revoke(path string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0) + _, _, e1 := syscall(funcPC(libc_revoke_trampoline), uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_revoke_trampoline() + +//go:linkname libc_revoke libc_revoke +//go:cgo_import_dynamic libc_revoke revoke "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Rmdir(path string) (err error) { @@ -924,64 +1304,78 @@ func Rmdir(path string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) + _, _, e1 := syscall(funcPC(libc_rmdir_trampoline), uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func libc_rmdir_trampoline() -func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { - r0, _, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(whence), 0, 0) - newoffset = int64(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} +//go:linkname libc_rmdir libc_rmdir +//go:cgo_import_dynamic libc_rmdir rmdir "libc.so" // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) { - _, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + _, _, e1 := syscall6(funcPC(libc_select_trampoline), uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_select_trampoline() + +//go:linkname libc_select libc_select +//go:cgo_import_dynamic libc_select select "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setegid(egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0) + _, _, e1 := rawSyscall(funcPC(libc_setegid_trampoline), uintptr(egid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_setegid_trampoline() + +//go:linkname libc_setegid libc_setegid +//go:cgo_import_dynamic libc_setegid setegid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Seteuid(euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0) + _, _, e1 := rawSyscall(funcPC(libc_seteuid_trampoline), uintptr(euid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_seteuid_trampoline() + +//go:linkname libc_seteuid libc_seteuid +//go:cgo_import_dynamic libc_seteuid seteuid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setgid(gid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0) + _, _, e1 := rawSyscall(funcPC(libc_setgid_trampoline), uintptr(gid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_setgid_trampoline() + +//go:linkname libc_setgid libc_setgid +//go:cgo_import_dynamic libc_setgid setgid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setlogin(name string) (err error) { @@ -990,67 +1384,97 @@ func Setlogin(name string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0) + _, _, e1 := syscall(funcPC(libc_setlogin_trampoline), uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_setlogin_trampoline() + +//go:linkname libc_setlogin libc_setlogin +//go:cgo_import_dynamic libc_setlogin setlogin "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) + _, _, e1 := rawSyscall(funcPC(libc_setpgid_trampoline), uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_setpgid_trampoline() + +//go:linkname libc_setpgid libc_setpgid +//go:cgo_import_dynamic libc_setpgid setpgid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { - _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) + _, _, e1 := syscall(funcPC(libc_setpriority_trampoline), uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } +func libc_setpriority_trampoline() + +//go:linkname libc_setpriority libc_setpriority +//go:cgo_import_dynamic libc_setpriority setpriority "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setregid(rgid int, egid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0) + _, _, e1 := rawSyscall(funcPC(libc_setregid_trampoline), uintptr(rgid), uintptr(egid), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_setregid_trampoline() + +//go:linkname libc_setregid libc_setregid +//go:cgo_import_dynamic libc_setregid setregid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setreuid(ruid int, euid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0) + _, _, e1 := rawSyscall(funcPC(libc_setreuid_trampoline), uintptr(ruid), uintptr(euid), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_setreuid_trampoline() + +//go:linkname libc_setreuid libc_setreuid +//go:cgo_import_dynamic libc_setreuid setreuid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setrlimit(which int, lim *Rlimit) (err error) { - _, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0) + _, _, e1 := rawSyscall(funcPC(libc_setrlimit_trampoline), uintptr(which), uintptr(unsafe.Pointer(lim)), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_setrlimit_trampoline() + +//go:linkname libc_setrlimit libc_setrlimit +//go:cgo_import_dynamic libc_setrlimit setrlimit "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { - r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) + r0, _, e1 := rawSyscall(funcPC(libc_setsid_trampoline), 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1058,26 +1482,41 @@ func Setsid() (pid int, err error) { return } +func libc_setsid_trampoline() + +//go:linkname libc_setsid libc_setsid +//go:cgo_import_dynamic libc_setsid setsid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tp *Timeval) (err error) { - _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0) + _, _, e1 := rawSyscall(funcPC(libc_settimeofday_trampoline), uintptr(unsafe.Pointer(tp)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_settimeofday_trampoline() + +//go:linkname libc_settimeofday libc_settimeofday +//go:cgo_import_dynamic libc_settimeofday settimeofday "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setuid(uid int) (err error) { - _, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0) + _, _, e1 := rawSyscall(funcPC(libc_setuid_trampoline), uintptr(uid), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_setuid_trampoline() + +//go:linkname libc_setuid libc_setuid +//go:cgo_import_dynamic libc_setuid setuid "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Stat(path string, stat *Stat_t) (err error) { @@ -1086,13 +1525,18 @@ func Stat(path string, stat *Stat_t) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + _, _, e1 := syscall(funcPC(libc_stat_trampoline), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_stat_trampoline() + +//go:linkname libc_stat libc_stat +//go:cgo_import_dynamic libc_stat stat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Statfs(path string, stat *Statfs_t) (err error) { @@ -1101,13 +1545,18 @@ func Statfs(path string, stat *Statfs_t) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_STATFS, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) + _, _, e1 := syscall(funcPC(libc_statfs_trampoline), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_statfs_trampoline() + +//go:linkname libc_statfs libc_statfs +//go:cgo_import_dynamic libc_statfs statfs "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Symlink(path string, link string) (err error) { @@ -1121,23 +1570,33 @@ func Symlink(path string, link string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) + _, _, e1 := syscall(funcPC(libc_symlink_trampoline), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_symlink_trampoline() + +//go:linkname libc_symlink libc_symlink +//go:cgo_import_dynamic libc_symlink symlink "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (err error) { - _, _, e1 := Syscall(SYS_SYNC, 0, 0, 0) + _, _, e1 := syscall(funcPC(libc_sync_trampoline), 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_sync_trampoline() + +//go:linkname libc_sync libc_sync +//go:cgo_import_dynamic libc_sync sync "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Truncate(path string, length int64) (err error) { @@ -1146,21 +1605,31 @@ func Truncate(path string, length int64) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length)) + _, _, e1 := syscall(funcPC(libc_truncate_trampoline), uintptr(unsafe.Pointer(_p0)), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_truncate_trampoline() + +//go:linkname libc_truncate libc_truncate +//go:cgo_import_dynamic libc_truncate truncate "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(newmask int) (oldmask int) { - r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0) + r0, _, _ := syscall(funcPC(libc_umask_trampoline), uintptr(newmask), 0, 0) oldmask = int(r0) return } +func libc_umask_trampoline() + +//go:linkname libc_umask libc_umask +//go:cgo_import_dynamic libc_umask umask "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unlink(path string) (err error) { @@ -1169,13 +1638,18 @@ func Unlink(path string) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0) + _, _, e1 := syscall(funcPC(libc_unlink_trampoline), uintptr(unsafe.Pointer(_p0)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_unlink_trampoline() + +//go:linkname libc_unlink libc_unlink +//go:cgo_import_dynamic libc_unlink unlink "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(path string, flags int) (err error) { @@ -1184,13 +1658,18 @@ func Unmount(path string, flags int) (err error) { if err != nil { return } - _, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) + _, _, e1 := syscall(funcPC(libc_unmount_trampoline), uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_unmount_trampoline() + +//go:linkname libc_unmount libc_unmount +//go:cgo_import_dynamic libc_unmount unmount "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { @@ -1200,7 +1679,7 @@ func write(fd int, p []byte) (n int, err error) { } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) + r0, _, e1 := syscall(funcPC(libc_write_trampoline), uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1208,10 +1687,15 @@ func write(fd int, p []byte) (n int, err error) { return } +func libc_write_trampoline() + +//go:linkname libc_write libc_write +//go:cgo_import_dynamic libc_write write "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) { - r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), 0, 0) + r0, _, e1 := syscall6X(funcPC(libc_mmap_trampoline), uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos)) ret = uintptr(r0) if e1 != 0 { err = errnoErr(e1) @@ -1219,53 +1703,78 @@ func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) ( return } +func libc_mmap_trampoline() + +//go:linkname libc_mmap libc_mmap +//go:cgo_import_dynamic libc_mmap mmap "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { - _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) + _, _, e1 := syscall(funcPC(libc_munmap_trampoline), uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_munmap_trampoline() + +//go:linkname libc_munmap libc_munmap +//go:cgo_import_dynamic libc_munmap munmap "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func readlen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) - n = int(r0) +func utimensat(dirfd int, path string, times *[2]Timespec, flag int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall6(funcPC(libc_utimensat_trampoline), uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flag), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_utimensat_trampoline() + +//go:linkname libc_utimensat libc_utimensat +//go:cgo_import_dynamic libc_utimensat utimensat "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func writelen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) - n = int(r0) +func directSyscall(trap uintptr, a1 uintptr, a2 uintptr, a3 uintptr, a4 uintptr, a5 uintptr) (ret uintptr, err error) { + r0, _, e1 := syscall6X(funcPC(libc_syscall_trampoline), uintptr(trap), uintptr(a1), uintptr(a2), uintptr(a3), uintptr(a4), uintptr(a5)) + ret = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_syscall_trampoline() + +//go:linkname libc_syscall libc_syscall +//go:cgo_import_dynamic libc_syscall syscall "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func utimensat(dirfd int, path string, times *[2]Timespec, flag int) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flag), 0, 0) +func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { + r0, _, e1 := syscallX(funcPC(libc_lseek_trampoline), uintptr(fd), uintptr(offset), uintptr(whence)) + newoffset = int64(r0) if e1 != 0 { err = errnoErr(e1) } return } +func libc_lseek_trampoline() + +//go:linkname libc_lseek libc_lseek +//go:cgo_import_dynamic libc_lseek lseek "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getcwd(buf []byte) (n int, err error) { @@ -1275,7 +1784,7 @@ func getcwd(buf []byte) (n int, err error) { } else { _p0 = unsafe.Pointer(&_zero) } - r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + r0, _, e1 := syscall(funcPC(libc_getcwd_trampoline), uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) @@ -1283,6 +1792,11 @@ func getcwd(buf []byte) (n int, err error) { return } +func libc_getcwd_trampoline() + +//go:linkname libc_getcwd libc_getcwd +//go:cgo_import_dynamic libc_getcwd getcwd "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { @@ -1292,9 +1806,184 @@ func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) } else { _p0 = unsafe.Pointer(&_zero) } - _, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + _, _, e1 := syscall6(funcPC(libc_sysctl_trampoline), uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +func libc_sysctl_trampoline() + +//go:linkname libc_sysctl libc_sysctl +//go:cgo_import_dynamic libc_sysctl sysctl "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func fork() (pid int, err error) { + r0, _, e1 := rawSyscall(funcPC(libc_fork_trampoline), 0, 0, 0) + pid = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +func libc_fork_trampoline() + +//go:linkname libc_fork libc_fork +//go:cgo_import_dynamic libc_fork fork "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func ioctl(fd int, req int, arg int) (err error) { + _, _, e1 := rawSyscall(funcPC(libc_ioctl_trampoline), uintptr(fd), uintptr(req), uintptr(arg)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +func libc_ioctl_trampoline() + +//go:linkname libc_ioctl libc_ioctl +//go:cgo_import_dynamic libc_ioctl ioctl "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func execve(path *byte, argv **byte, envp **byte) (err error) { + _, _, e1 := rawSyscall(funcPC(libc_execve_trampoline), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(argv)), uintptr(unsafe.Pointer(envp))) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +func libc_execve_trampoline() + +//go:linkname libc_execve libc_execve +//go:cgo_import_dynamic libc_execve execve "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func exit(res int) (err error) { + _, _, e1 := rawSyscall(funcPC(libc_exit_trampoline), uintptr(res), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +func libc_exit_trampoline() + +//go:linkname libc_exit libc_exit +//go:cgo_import_dynamic libc_exit exit "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +//go:nosplit +func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { + _, _, e1 := syscall6(funcPC(libc_ptrace_trampoline), uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +func libc_ptrace_trampoline() + +//go:linkname libc_ptrace libc_ptrace +//go:cgo_import_dynamic libc_ptrace ptrace "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func getentropy(p []byte) (err error) { + var _p0 unsafe.Pointer + if len(p) > 0 { + _p0 = unsafe.Pointer(&p[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + _, _, e1 := rawSyscall(funcPC(libc_getentropy_trampoline), uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } + +func libc_getentropy_trampoline() + +//go:linkname libc_getentropy libc_getentropy +//go:cgo_import_dynamic libc_getentropy getentropy "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall6(funcPC(libc_fstatat_trampoline), uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +func libc_fstatat_trampoline() + +//go:linkname libc_fstatat libc_fstatat +//go:cgo_import_dynamic libc_fstatat fstatat "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (val int, err error) { + r0, _, e1 := syscall(funcPC(libc_fcntl_trampoline), uintptr(fd), uintptr(cmd), uintptr(arg)) + val = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func unlinkat(fd int, path string, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := syscall(funcPC(libc_unlinkat_trampoline), uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +func libc_unlinkat_trampoline() + +//go:linkname libc_unlinkat libc_unlinkat +//go:cgo_import_dynamic libc_unlinkat unlinkat "libc.so" + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func openat(fd int, path string, flags int, perm uint32) (fdret int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall6(funcPC(libc_openat_trampoline), uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(perm), 0, 0) + fdret = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +func libc_openat_trampoline() + +//go:linkname libc_openat libc_openat +//go:cgo_import_dynamic libc_openat openat "libc.so" diff --git a/src/syscall/zsyscall_openbsd_arm64.s b/src/syscall/zsyscall_openbsd_arm64.s new file mode 100644 index 0000000000..37778b1db5 --- /dev/null +++ b/src/syscall/zsyscall_openbsd_arm64.s @@ -0,0 +1,233 @@ +// go run mkasm.go openbsd arm64 +// Code generated by the command above; DO NOT EDIT. +#include "textflag.h" +TEXT ·libc_getgroups_trampoline(SB),NOSPLIT,$0-0 + JMP libc_getgroups(SB) +TEXT ·libc_setgroups_trampoline(SB),NOSPLIT,$0-0 + JMP libc_setgroups(SB) +TEXT ·libc_wait4_trampoline(SB),NOSPLIT,$0-0 + JMP libc_wait4(SB) +TEXT ·libc_accept_trampoline(SB),NOSPLIT,$0-0 + JMP libc_accept(SB) +TEXT ·libc_bind_trampoline(SB),NOSPLIT,$0-0 + JMP libc_bind(SB) +TEXT ·libc_connect_trampoline(SB),NOSPLIT,$0-0 + JMP libc_connect(SB) +TEXT ·libc_socket_trampoline(SB),NOSPLIT,$0-0 + JMP libc_socket(SB) +TEXT ·libc_getsockopt_trampoline(SB),NOSPLIT,$0-0 + JMP libc_getsockopt(SB) +TEXT ·libc_setsockopt_trampoline(SB),NOSPLIT,$0-0 + JMP libc_setsockopt(SB) +TEXT ·libc_getpeername_trampoline(SB),NOSPLIT,$0-0 + JMP libc_getpeername(SB) +TEXT ·libc_getsockname_trampoline(SB),NOSPLIT,$0-0 + JMP libc_getsockname(SB) +TEXT ·libc_shutdown_trampoline(SB),NOSPLIT,$0-0 + JMP libc_shutdown(SB) +TEXT ·libc_socketpair_trampoline(SB),NOSPLIT,$0-0 + JMP libc_socketpair(SB) +TEXT ·libc_recvfrom_trampoline(SB),NOSPLIT,$0-0 + JMP libc_recvfrom(SB) +TEXT ·libc_sendto_trampoline(SB),NOSPLIT,$0-0 + JMP libc_sendto(SB) +TEXT ·libc_recvmsg_trampoline(SB),NOSPLIT,$0-0 + JMP libc_recvmsg(SB) +TEXT ·libc_sendmsg_trampoline(SB),NOSPLIT,$0-0 + JMP libc_sendmsg(SB) +TEXT ·libc_kevent_trampoline(SB),NOSPLIT,$0-0 + JMP libc_kevent(SB) +TEXT ·libc_utimes_trampoline(SB),NOSPLIT,$0-0 + JMP libc_utimes(SB) +TEXT ·libc_futimes_trampoline(SB),NOSPLIT,$0-0 + JMP libc_futimes(SB) +TEXT ·libc_fcntl_trampoline(SB),NOSPLIT,$0-0 + JMP libc_fcntl(SB) +TEXT ·libc_pipe2_trampoline(SB),NOSPLIT,$0-0 + JMP libc_pipe2(SB) +TEXT ·libc_accept4_trampoline(SB),NOSPLIT,$0-0 + JMP libc_accept4(SB) +TEXT ·libc_getdents_trampoline(SB),NOSPLIT,$0-0 + JMP libc_getdents(SB) +TEXT ·libc_access_trampoline(SB),NOSPLIT,$0-0 + JMP libc_access(SB) +TEXT ·libc_adjtime_trampoline(SB),NOSPLIT,$0-0 + JMP libc_adjtime(SB) +TEXT ·libc_chdir_trampoline(SB),NOSPLIT,$0-0 + JMP libc_chdir(SB) +TEXT ·libc_chflags_trampoline(SB),NOSPLIT,$0-0 + JMP libc_chflags(SB) +TEXT ·libc_chmod_trampoline(SB),NOSPLIT,$0-0 + JMP libc_chmod(SB) +TEXT ·libc_chown_trampoline(SB),NOSPLIT,$0-0 + JMP libc_chown(SB) +TEXT ·libc_chroot_trampoline(SB),NOSPLIT,$0-0 + JMP libc_chroot(SB) +TEXT ·libc_close_trampoline(SB),NOSPLIT,$0-0 + JMP libc_close(SB) +TEXT ·libc_dup_trampoline(SB),NOSPLIT,$0-0 + JMP libc_dup(SB) +TEXT ·libc_dup2_trampoline(SB),NOSPLIT,$0-0 + JMP libc_dup2(SB) +TEXT ·libc_fchdir_trampoline(SB),NOSPLIT,$0-0 + JMP libc_fchdir(SB) +TEXT ·libc_fchflags_trampoline(SB),NOSPLIT,$0-0 + JMP libc_fchflags(SB) +TEXT ·libc_fchmod_trampoline(SB),NOSPLIT,$0-0 + JMP libc_fchmod(SB) +TEXT ·libc_fchown_trampoline(SB),NOSPLIT,$0-0 + JMP libc_fchown(SB) +TEXT ·libc_flock_trampoline(SB),NOSPLIT,$0-0 + JMP libc_flock(SB) +TEXT ·libc_fpathconf_trampoline(SB),NOSPLIT,$0-0 + JMP libc_fpathconf(SB) +TEXT ·libc_fstat_trampoline(SB),NOSPLIT,$0-0 + JMP libc_fstat(SB) +TEXT ·libc_fstatfs_trampoline(SB),NOSPLIT,$0-0 + JMP libc_fstatfs(SB) +TEXT ·libc_fsync_trampoline(SB),NOSPLIT,$0-0 + JMP libc_fsync(SB) +TEXT ·libc_ftruncate_trampoline(SB),NOSPLIT,$0-0 + JMP libc_ftruncate(SB) +TEXT ·libc_getegid_trampoline(SB),NOSPLIT,$0-0 + JMP libc_getegid(SB) +TEXT ·libc_geteuid_trampoline(SB),NOSPLIT,$0-0 + JMP libc_geteuid(SB) +TEXT ·libc_getgid_trampoline(SB),NOSPLIT,$0-0 + JMP libc_getgid(SB) +TEXT ·libc_getpgid_trampoline(SB),NOSPLIT,$0-0 + JMP libc_getpgid(SB) +TEXT ·libc_getpgrp_trampoline(SB),NOSPLIT,$0-0 + JMP libc_getpgrp(SB) +TEXT ·libc_getpid_trampoline(SB),NOSPLIT,$0-0 + JMP libc_getpid(SB) +TEXT ·libc_getppid_trampoline(SB),NOSPLIT,$0-0 + JMP libc_getppid(SB) +TEXT ·libc_getpriority_trampoline(SB),NOSPLIT,$0-0 + JMP libc_getpriority(SB) +TEXT ·libc_getrlimit_trampoline(SB),NOSPLIT,$0-0 + JMP libc_getrlimit(SB) +TEXT ·libc_getrusage_trampoline(SB),NOSPLIT,$0-0 + JMP libc_getrusage(SB) +TEXT ·libc_getsid_trampoline(SB),NOSPLIT,$0-0 + JMP libc_getsid(SB) +TEXT ·libc_gettimeofday_trampoline(SB),NOSPLIT,$0-0 + JMP libc_gettimeofday(SB) +TEXT ·libc_getuid_trampoline(SB),NOSPLIT,$0-0 + JMP libc_getuid(SB) +TEXT ·libc_issetugid_trampoline(SB),NOSPLIT,$0-0 + JMP libc_issetugid(SB) +TEXT ·libc_kill_trampoline(SB),NOSPLIT,$0-0 + JMP libc_kill(SB) +TEXT ·libc_kqueue_trampoline(SB),NOSPLIT,$0-0 + JMP libc_kqueue(SB) +TEXT ·libc_lchown_trampoline(SB),NOSPLIT,$0-0 + JMP libc_lchown(SB) +TEXT ·libc_link_trampoline(SB),NOSPLIT,$0-0 + JMP libc_link(SB) +TEXT ·libc_listen_trampoline(SB),NOSPLIT,$0-0 + JMP libc_listen(SB) +TEXT ·libc_lstat_trampoline(SB),NOSPLIT,$0-0 + JMP libc_lstat(SB) +TEXT ·libc_mkdir_trampoline(SB),NOSPLIT,$0-0 + JMP libc_mkdir(SB) +TEXT ·libc_mkfifo_trampoline(SB),NOSPLIT,$0-0 + JMP libc_mkfifo(SB) +TEXT ·libc_mknod_trampoline(SB),NOSPLIT,$0-0 + JMP libc_mknod(SB) +TEXT ·libc_nanosleep_trampoline(SB),NOSPLIT,$0-0 + JMP libc_nanosleep(SB) +TEXT ·libc_open_trampoline(SB),NOSPLIT,$0-0 + JMP libc_open(SB) +TEXT ·libc_pathconf_trampoline(SB),NOSPLIT,$0-0 + JMP libc_pathconf(SB) +TEXT ·libc_pread_trampoline(SB),NOSPLIT,$0-0 + JMP libc_pread(SB) +TEXT ·libc_pwrite_trampoline(SB),NOSPLIT,$0-0 + JMP libc_pwrite(SB) +TEXT ·libc_read_trampoline(SB),NOSPLIT,$0-0 + JMP libc_read(SB) +TEXT ·libc_readlink_trampoline(SB),NOSPLIT,$0-0 + JMP libc_readlink(SB) +TEXT ·libc_rename_trampoline(SB),NOSPLIT,$0-0 + JMP libc_rename(SB) +TEXT ·libc_revoke_trampoline(SB),NOSPLIT,$0-0 + JMP libc_revoke(SB) +TEXT ·libc_rmdir_trampoline(SB),NOSPLIT,$0-0 + JMP libc_rmdir(SB) +TEXT ·libc_select_trampoline(SB),NOSPLIT,$0-0 + JMP libc_select(SB) +TEXT ·libc_setegid_trampoline(SB),NOSPLIT,$0-0 + JMP libc_setegid(SB) +TEXT ·libc_seteuid_trampoline(SB),NOSPLIT,$0-0 + JMP libc_seteuid(SB) +TEXT ·libc_setgid_trampoline(SB),NOSPLIT,$0-0 + JMP libc_setgid(SB) +TEXT ·libc_setlogin_trampoline(SB),NOSPLIT,$0-0 + JMP libc_setlogin(SB) +TEXT ·libc_setpgid_trampoline(SB),NOSPLIT,$0-0 + JMP libc_setpgid(SB) +TEXT ·libc_setpriority_trampoline(SB),NOSPLIT,$0-0 + JMP libc_setpriority(SB) +TEXT ·libc_setregid_trampoline(SB),NOSPLIT,$0-0 + JMP libc_setregid(SB) +TEXT ·libc_setreuid_trampoline(SB),NOSPLIT,$0-0 + JMP libc_setreuid(SB) +TEXT ·libc_setrlimit_trampoline(SB),NOSPLIT,$0-0 + JMP libc_setrlimit(SB) +TEXT ·libc_setsid_trampoline(SB),NOSPLIT,$0-0 + JMP libc_setsid(SB) +TEXT ·libc_settimeofday_trampoline(SB),NOSPLIT,$0-0 + JMP libc_settimeofday(SB) +TEXT ·libc_setuid_trampoline(SB),NOSPLIT,$0-0 + JMP libc_setuid(SB) +TEXT ·libc_stat_trampoline(SB),NOSPLIT,$0-0 + JMP libc_stat(SB) +TEXT ·libc_statfs_trampoline(SB),NOSPLIT,$0-0 + JMP libc_statfs(SB) +TEXT ·libc_symlink_trampoline(SB),NOSPLIT,$0-0 + JMP libc_symlink(SB) +TEXT ·libc_sync_trampoline(SB),NOSPLIT,$0-0 + JMP libc_sync(SB) +TEXT ·libc_truncate_trampoline(SB),NOSPLIT,$0-0 + JMP libc_truncate(SB) +TEXT ·libc_umask_trampoline(SB),NOSPLIT,$0-0 + JMP libc_umask(SB) +TEXT ·libc_unlink_trampoline(SB),NOSPLIT,$0-0 + JMP libc_unlink(SB) +TEXT ·libc_unmount_trampoline(SB),NOSPLIT,$0-0 + JMP libc_unmount(SB) +TEXT ·libc_write_trampoline(SB),NOSPLIT,$0-0 + JMP libc_write(SB) +TEXT ·libc_mmap_trampoline(SB),NOSPLIT,$0-0 + JMP libc_mmap(SB) +TEXT ·libc_munmap_trampoline(SB),NOSPLIT,$0-0 + JMP libc_munmap(SB) +TEXT ·libc_utimensat_trampoline(SB),NOSPLIT,$0-0 + JMP libc_utimensat(SB) +TEXT ·libc_syscall_trampoline(SB),NOSPLIT,$0-0 + JMP libc_syscall(SB) +TEXT ·libc_lseek_trampoline(SB),NOSPLIT,$0-0 + JMP libc_lseek(SB) +TEXT ·libc_getcwd_trampoline(SB),NOSPLIT,$0-0 + JMP libc_getcwd(SB) +TEXT ·libc_sysctl_trampoline(SB),NOSPLIT,$0-0 + JMP libc_sysctl(SB) +TEXT ·libc_fork_trampoline(SB),NOSPLIT,$0-0 + JMP libc_fork(SB) +TEXT ·libc_ioctl_trampoline(SB),NOSPLIT,$0-0 + JMP libc_ioctl(SB) +TEXT ·libc_execve_trampoline(SB),NOSPLIT,$0-0 + JMP libc_execve(SB) +TEXT ·libc_exit_trampoline(SB),NOSPLIT,$0-0 + JMP libc_exit(SB) +TEXT ·libc_ptrace_trampoline(SB),NOSPLIT,$0-0 + JMP libc_ptrace(SB) +TEXT ·libc_getentropy_trampoline(SB),NOSPLIT,$0-0 + JMP libc_getentropy(SB) +TEXT ·libc_fstatat_trampoline(SB),NOSPLIT,$0-0 + JMP libc_fstatat(SB) +TEXT ·libc_unlinkat_trampoline(SB),NOSPLIT,$0-0 + JMP libc_unlinkat(SB) +TEXT ·libc_openat_trampoline(SB),NOSPLIT,$0-0 + JMP libc_openat(SB) -- cgit v1.2.3-54-g00ecf From 4b068cafb5a5e094dd0b7ed37ff73e08309a39e7 Mon Sep 17 00:00:00 2001 From: Ian Lance Taylor Date: Wed, 27 Jan 2021 13:54:10 -0800 Subject: doc/go1.16: document go/build/constraint package For #40700 For #41184 Fixes #43957 Change-Id: Ia346f4cf160431b721efeba7dc5f1fb8814efd95 Reviewed-on: https://go-review.googlesource.com/c/go/+/287472 Trust: Ian Lance Taylor Reviewed-by: Russ Cox Reviewed-by: Dmitri Shuralyov --- doc/go1.16.html | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/doc/go1.16.html b/doc/go1.16.html index 3a45940479..6cc75b4865 100644 --- a/doc/go1.16.html +++ b/doc/go1.16.html @@ -762,6 +762,25 @@ func TestFoo(t *testing.T) { +
go/build/constraint
+
+

+ The new + go/build/constraint + package parses build constraint lines, both the original + // +build syntax and the //go:build + syntax that will be introduced in Go 1.17. + This package exists so that tools built with Go 1.16 will be able + to process Go 1.17 source code. + See https://golang.org/design/draft-gobuild + for details about the build constraint syntaxes and the planned + transition to the //go:build syntax. + Note that //go:build lines are not supported + in Go 1.16 and should not be introduced into Go programs yet. +

+
+
+
html/template

-- cgit v1.2.3-54-g00ecf From 725a642c2d0b42e2b4435dfbfbff6b138d37d2ce Mon Sep 17 00:00:00 2001 From: Joel Sing Date: Wed, 27 Jan 2021 23:09:57 +1100 Subject: runtime: correct syscall10/syscall10X on openbsd/amd64 The syscall10/syscall10X implementation uses an incorrect stack offset for arguments a7 to a10. Correct this so that the syscall arguments work as intended. Updates #36435 Fixes #43927 Change-Id: Ia7ae6cc8c89f50acfd951c0f271f3b3309934499 Reviewed-on: https://go-review.googlesource.com/c/go/+/287252 Trust: Joel Sing Reviewed-by: Cherry Zhang --- src/runtime/sys_openbsd_amd64.s | 36 ++++++++++++++++++++++-------------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/src/runtime/sys_openbsd_amd64.s b/src/runtime/sys_openbsd_amd64.s index 534645eec4..b3a76b57a3 100644 --- a/src/runtime/sys_openbsd_amd64.s +++ b/src/runtime/sys_openbsd_amd64.s @@ -676,27 +676,31 @@ TEXT runtime·syscall10(SB),NOSPLIT,$0 PUSHQ BP MOVQ SP, BP SUBQ $48, SP + + // Arguments a1 to a6 get passed in registers, with a7 onwards being + // passed via the stack per the x86-64 System V ABI + // (https://github.com/hjl-tools/x86-psABI/wiki/x86-64-psABI-1.0.pdf). MOVQ (7*8)(DI), R10 // a7 MOVQ (8*8)(DI), R11 // a8 MOVQ (9*8)(DI), R12 // a9 MOVQ (10*8)(DI), R13 // a10 - MOVQ R10, (1*8)(SP) // a7 - MOVQ R11, (2*8)(SP) // a8 - MOVQ R12, (3*8)(SP) // a9 - MOVQ R13, (4*8)(SP) // a10 + MOVQ R10, (0*8)(SP) // a7 + MOVQ R11, (1*8)(SP) // a8 + MOVQ R12, (2*8)(SP) // a9 + MOVQ R13, (3*8)(SP) // a10 MOVQ (0*8)(DI), R11 // fn MOVQ (2*8)(DI), SI // a2 MOVQ (3*8)(DI), DX // a3 MOVQ (4*8)(DI), CX // a4 MOVQ (5*8)(DI), R8 // a5 MOVQ (6*8)(DI), R9 // a6 - MOVQ DI, (SP) + MOVQ DI, (4*8)(SP) MOVQ (1*8)(DI), DI // a1 XORL AX, AX // vararg: say "no float args" CALL R11 - MOVQ (SP), DI + MOVQ (4*8)(SP), DI MOVQ AX, (11*8)(DI) // r1 MOVQ DX, (12*8)(DI) // r2 @@ -705,7 +709,7 @@ TEXT runtime·syscall10(SB),NOSPLIT,$0 CALL libc_errno(SB) MOVLQSX (AX), AX - MOVQ (SP), DI + MOVQ (4*8)(SP), DI MOVQ AX, (13*8)(DI) // err ok: @@ -741,27 +745,31 @@ TEXT runtime·syscall10X(SB),NOSPLIT,$0 PUSHQ BP MOVQ SP, BP SUBQ $48, SP + + // Arguments a1 to a6 get passed in registers, with a7 onwards being + // passed via the stack per the x86-64 System V ABI + // (https://github.com/hjl-tools/x86-psABI/wiki/x86-64-psABI-1.0.pdf). MOVQ (7*8)(DI), R10 // a7 MOVQ (8*8)(DI), R11 // a8 MOVQ (9*8)(DI), R12 // a9 MOVQ (10*8)(DI), R13 // a10 - MOVQ R10, (1*8)(SP) // a7 - MOVQ R11, (2*8)(SP) // a8 - MOVQ R12, (3*8)(SP) // a9 - MOVQ R13, (4*8)(SP) // a10 + MOVQ R10, (0*8)(SP) // a7 + MOVQ R11, (1*8)(SP) // a8 + MOVQ R12, (2*8)(SP) // a9 + MOVQ R13, (3*8)(SP) // a10 MOVQ (0*8)(DI), R11 // fn MOVQ (2*8)(DI), SI // a2 MOVQ (3*8)(DI), DX // a3 MOVQ (4*8)(DI), CX // a4 MOVQ (5*8)(DI), R8 // a5 MOVQ (6*8)(DI), R9 // a6 - MOVQ DI, (SP) + MOVQ DI, (4*8)(SP) MOVQ (1*8)(DI), DI // a1 XORL AX, AX // vararg: say "no float args" CALL R11 - MOVQ (SP), DI + MOVQ (4*8)(SP), DI MOVQ AX, (11*8)(DI) // r1 MOVQ DX, (12*8)(DI) // r2 @@ -770,7 +778,7 @@ TEXT runtime·syscall10X(SB),NOSPLIT,$0 CALL libc_errno(SB) MOVLQSX (AX), AX - MOVQ (SP), DI + MOVQ (4*8)(SP), DI MOVQ AX, (13*8)(DI) // err ok: -- cgit v1.2.3-54-g00ecf From 41bb49b878ce4dd24c0055aaf734577d3fb37d50 Mon Sep 17 00:00:00 2001 From: "Bryan C. Mills" Date: Thu, 28 Jan 2021 11:14:23 -0500 Subject: cmd/go: revert TestScript/build_trimpath to use ioutil.ReadFile This call was changed to os.ReadFile in CL 266365, but the test also builds that source file using gccgo if present, and released versions of gccgo do not yet support ioutil.ReadFile. Manually tested with gccgo gccgo 10.2.1 (see #35786). Fixes #43974. Updates #42026. Change-Id: Ic4ca0848d3ca324e2ab10fd14ad867f21e0898e3 Reviewed-on: https://go-review.googlesource.com/c/go/+/287613 Trust: Bryan C. Mills Run-TryBot: Bryan C. Mills Reviewed-by: Jay Conrod TryBot-Result: Go Bot --- src/cmd/go/testdata/script/build_trimpath.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cmd/go/testdata/script/build_trimpath.txt b/src/cmd/go/testdata/script/build_trimpath.txt index e1ea0a48b2..2c3bee8fdc 100644 --- a/src/cmd/go/testdata/script/build_trimpath.txt +++ b/src/cmd/go/testdata/script/build_trimpath.txt @@ -121,6 +121,7 @@ package main import ( "bytes" "fmt" + "io/ioutil" "log" "os" "os/exec" @@ -130,7 +131,7 @@ import ( func main() { exe := os.Args[1] - data, err := os.ReadFile(exe) + data, err := ioutil.ReadFile(exe) if err != nil { log.Fatal(err) } -- cgit v1.2.3-54-g00ecf From c8bd8010ff7c0115bf186443119216ba51f09d2b Mon Sep 17 00:00:00 2001 From: Joel Sing Date: Thu, 28 Jan 2021 19:19:47 +1100 Subject: syscall: generate readlen/writelen for openbsd libc Rather than hand rolling readlen and writelen, move it to being generated via mksyscall.pl, as is done for most other functions. Updates #36435 Change-Id: I649aed7b182b41c8639686feae25ce19dab812c3 Reviewed-on: https://go-review.googlesource.com/c/go/+/287532 Trust: Joel Sing Reviewed-by: Cherry Zhang Run-TryBot: Cherry Zhang TryBot-Result: Go Bot --- src/syscall/syscall_openbsd_libc.go | 28 ++++++---------------------- src/syscall/zsyscall_openbsd_amd64.go | 22 ++++++++++++++++++++++ src/syscall/zsyscall_openbsd_arm64.go | 22 ++++++++++++++++++++++ 3 files changed, 50 insertions(+), 22 deletions(-) diff --git a/src/syscall/syscall_openbsd_libc.go b/src/syscall/syscall_openbsd_libc.go index 2fcc2011bc..042615bf2a 100644 --- a/src/syscall/syscall_openbsd_libc.go +++ b/src/syscall/syscall_openbsd_libc.go @@ -8,6 +8,10 @@ package syscall import "unsafe" +func init() { + execveOpenBSD = execve +} + //sys directSyscall(trap uintptr, a1 uintptr, a2 uintptr, a3 uintptr, a4 uintptr, a5 uintptr) (ret uintptr, err error) = SYS_syscall func syscallInternal(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno) { @@ -56,6 +60,8 @@ func funcPC(f func()) uintptr { return **(**uintptr)(unsafe.Pointer(&f)) } +//sys readlen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_read +//sys writelen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_write //sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = SYS_lseek //sys getcwd(buf []byte) (n int, err error) //sys sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) @@ -69,25 +75,3 @@ func funcPC(f func()) uintptr { //sys fcntlPtr(fd int, cmd int, arg unsafe.Pointer) (val int, err error) = SYS_fcntl //sys unlinkat(fd int, path string, flags int) (err error) //sys openat(fd int, path string, flags int, perm uint32) (fdret int, err error) - -func init() { - execveOpenBSD = execve -} - -func readlen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := syscall(funcPC(libc_read_trampoline), uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -func writelen(fd int, buf *byte, nbuf int) (n int, err error) { - r0, _, e1 := syscall(funcPC(libc_write_trampoline), uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} diff --git a/src/syscall/zsyscall_openbsd_amd64.go b/src/syscall/zsyscall_openbsd_amd64.go index 67dc0d3733..733050ad1d 100644 --- a/src/syscall/zsyscall_openbsd_amd64.go +++ b/src/syscall/zsyscall_openbsd_amd64.go @@ -1761,6 +1761,28 @@ func libc_syscall_trampoline() // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func readlen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := syscall(funcPC(libc_read_trampoline), uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writelen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := syscall(funcPC(libc_write_trampoline), uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { r0, _, e1 := syscallX(funcPC(libc_lseek_trampoline), uintptr(fd), uintptr(offset), uintptr(whence)) newoffset = int64(r0) diff --git a/src/syscall/zsyscall_openbsd_arm64.go b/src/syscall/zsyscall_openbsd_arm64.go index 90a46f3c4b..2093eb74e5 100644 --- a/src/syscall/zsyscall_openbsd_arm64.go +++ b/src/syscall/zsyscall_openbsd_arm64.go @@ -1761,6 +1761,28 @@ func libc_syscall_trampoline() // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func readlen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := syscall(funcPC(libc_read_trampoline), uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writelen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := syscall(funcPC(libc_write_trampoline), uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { r0, _, e1 := syscallX(funcPC(libc_lseek_trampoline), uintptr(fd), uintptr(offset), uintptr(whence)) newoffset = int64(r0) -- cgit v1.2.3-54-g00ecf From 68058edc39edae96e34225ca163002233b623c97 Mon Sep 17 00:00:00 2001 From: Cherry Zhang Date: Thu, 28 Jan 2021 14:57:55 -0500 Subject: runtime: document pointer write atomicity for memclrNoHeapPointers memclrNoHeapPointers is the underlying implementation of typedmemclr and memclrHasPointers, so it still needs to write pointer-aligned words atomically. Document this requirement. Updates #41428. Change-Id: Ice00dee5de7a96a50e51ff019fcef069e8a8406a Reviewed-on: https://go-review.googlesource.com/c/go/+/287692 Trust: Cherry Zhang Reviewed-by: Keith Randall --- src/runtime/memclr_386.s | 2 ++ src/runtime/memclr_amd64.s | 2 ++ src/runtime/memclr_arm.s | 2 ++ src/runtime/memclr_arm64.s | 2 ++ src/runtime/memclr_mips64x.s | 2 ++ src/runtime/memclr_mipsx.s | 2 ++ src/runtime/memclr_plan9_386.s | 2 ++ src/runtime/memclr_plan9_amd64.s | 2 ++ src/runtime/memclr_ppc64x.s | 2 ++ src/runtime/memclr_riscv64.s | 2 ++ src/runtime/memclr_s390x.s | 2 ++ src/runtime/memclr_wasm.s | 2 ++ src/runtime/stubs.go | 8 ++++++++ 13 files changed, 32 insertions(+) diff --git a/src/runtime/memclr_386.s b/src/runtime/memclr_386.s index 65f7196312..5e090ef09e 100644 --- a/src/runtime/memclr_386.s +++ b/src/runtime/memclr_386.s @@ -9,6 +9,8 @@ // NOTE: Windows externalthreadhandler expects memclr to preserve DX. +// See memclrNoHeapPointers Go doc for important implementation constraints. + // func memclrNoHeapPointers(ptr unsafe.Pointer, n uintptr) TEXT runtime·memclrNoHeapPointers(SB), NOSPLIT, $0-8 MOVL ptr+0(FP), DI diff --git a/src/runtime/memclr_amd64.s b/src/runtime/memclr_amd64.s index d79078fd00..37fe9745b1 100644 --- a/src/runtime/memclr_amd64.s +++ b/src/runtime/memclr_amd64.s @@ -9,6 +9,8 @@ // NOTE: Windows externalthreadhandler expects memclr to preserve DX. +// See memclrNoHeapPointers Go doc for important implementation constraints. + // func memclrNoHeapPointers(ptr unsafe.Pointer, n uintptr) TEXT runtime·memclrNoHeapPointers(SB), NOSPLIT, $0-16 MOVQ ptr+0(FP), DI diff --git a/src/runtime/memclr_arm.s b/src/runtime/memclr_arm.s index 7326b8be34..f113a1aa2d 100644 --- a/src/runtime/memclr_arm.s +++ b/src/runtime/memclr_arm.s @@ -30,6 +30,8 @@ #define N R12 #define TMP R12 /* N and TMP don't overlap */ +// See memclrNoHeapPointers Go doc for important implementation constraints. + // func memclrNoHeapPointers(ptr unsafe.Pointer, n uintptr) TEXT runtime·memclrNoHeapPointers(SB),NOSPLIT,$0-8 MOVW ptr+0(FP), TO diff --git a/src/runtime/memclr_arm64.s b/src/runtime/memclr_arm64.s index a56a6dfb85..bef77651e4 100644 --- a/src/runtime/memclr_arm64.s +++ b/src/runtime/memclr_arm64.s @@ -4,6 +4,8 @@ #include "textflag.h" +// See memclrNoHeapPointers Go doc for important implementation constraints. + // func memclrNoHeapPointers(ptr unsafe.Pointer, n uintptr) TEXT runtime·memclrNoHeapPointers(SB),NOSPLIT,$0-16 MOVD ptr+0(FP), R0 diff --git a/src/runtime/memclr_mips64x.s b/src/runtime/memclr_mips64x.s index 4c2292eae8..d7a3251e20 100644 --- a/src/runtime/memclr_mips64x.s +++ b/src/runtime/memclr_mips64x.s @@ -7,6 +7,8 @@ #include "go_asm.h" #include "textflag.h" +// See memclrNoHeapPointers Go doc for important implementation constraints. + // func memclrNoHeapPointers(ptr unsafe.Pointer, n uintptr) TEXT runtime·memclrNoHeapPointers(SB),NOSPLIT,$0-16 MOVV ptr+0(FP), R1 diff --git a/src/runtime/memclr_mipsx.s b/src/runtime/memclr_mipsx.s index 1561a23dbe..eb2a8a7219 100644 --- a/src/runtime/memclr_mipsx.s +++ b/src/runtime/memclr_mipsx.s @@ -14,6 +14,8 @@ #define MOVWLO MOVWL #endif +// See memclrNoHeapPointers Go doc for important implementation constraints. + // func memclrNoHeapPointers(ptr unsafe.Pointer, n uintptr) TEXT runtime·memclrNoHeapPointers(SB),NOSPLIT,$0-8 MOVW n+4(FP), R2 diff --git a/src/runtime/memclr_plan9_386.s b/src/runtime/memclr_plan9_386.s index 5b880ae86f..54701a9453 100644 --- a/src/runtime/memclr_plan9_386.s +++ b/src/runtime/memclr_plan9_386.s @@ -4,6 +4,8 @@ #include "textflag.h" +// See memclrNoHeapPointers Go doc for important implementation constraints. + // func memclrNoHeapPointers(ptr unsafe.Pointer, n uintptr) TEXT runtime·memclrNoHeapPointers(SB), NOSPLIT, $0-8 MOVL ptr+0(FP), DI diff --git a/src/runtime/memclr_plan9_amd64.s b/src/runtime/memclr_plan9_amd64.s index ad383cd6b3..8c6a1cc780 100644 --- a/src/runtime/memclr_plan9_amd64.s +++ b/src/runtime/memclr_plan9_amd64.s @@ -4,6 +4,8 @@ #include "textflag.h" +// See memclrNoHeapPointers Go doc for important implementation constraints. + // func memclrNoHeapPointers(ptr unsafe.Pointer, n uintptr) TEXT runtime·memclrNoHeapPointers(SB),NOSPLIT,$0-16 MOVQ ptr+0(FP), DI diff --git a/src/runtime/memclr_ppc64x.s b/src/runtime/memclr_ppc64x.s index 072963f756..7512620894 100644 --- a/src/runtime/memclr_ppc64x.s +++ b/src/runtime/memclr_ppc64x.s @@ -6,6 +6,8 @@ #include "textflag.h" +// See memclrNoHeapPointers Go doc for important implementation constraints. + // func memclrNoHeapPointers(ptr unsafe.Pointer, n uintptr) TEXT runtime·memclrNoHeapPointers(SB), NOSPLIT|NOFRAME, $0-16 MOVD ptr+0(FP), R3 diff --git a/src/runtime/memclr_riscv64.s b/src/runtime/memclr_riscv64.s index ba7704e805..54ddaa4560 100644 --- a/src/runtime/memclr_riscv64.s +++ b/src/runtime/memclr_riscv64.s @@ -4,6 +4,8 @@ #include "textflag.h" +// See memclrNoHeapPointers Go doc for important implementation constraints. + // void runtime·memclrNoHeapPointers(void*, uintptr) TEXT runtime·memclrNoHeapPointers(SB),NOSPLIT,$0-16 MOV ptr+0(FP), T1 diff --git a/src/runtime/memclr_s390x.s b/src/runtime/memclr_s390x.s index dd14a441cc..fa657ef66e 100644 --- a/src/runtime/memclr_s390x.s +++ b/src/runtime/memclr_s390x.s @@ -4,6 +4,8 @@ #include "textflag.h" +// See memclrNoHeapPointers Go doc for important implementation constraints. + // func memclrNoHeapPointers(ptr unsafe.Pointer, n uintptr) TEXT runtime·memclrNoHeapPointers(SB),NOSPLIT|NOFRAME,$0-16 MOVD ptr+0(FP), R4 diff --git a/src/runtime/memclr_wasm.s b/src/runtime/memclr_wasm.s index 68ffe2f67b..5a053049f8 100644 --- a/src/runtime/memclr_wasm.s +++ b/src/runtime/memclr_wasm.s @@ -4,6 +4,8 @@ #include "textflag.h" +// See memclrNoHeapPointers Go doc for important implementation constraints. + // func memclrNoHeapPointers(ptr unsafe.Pointer, n uintptr) TEXT runtime·memclrNoHeapPointers(SB), NOSPLIT, $0-16 MOVD ptr+0(FP), R0 diff --git a/src/runtime/stubs.go b/src/runtime/stubs.go index b55c3c0590..2ee2c74dfe 100644 --- a/src/runtime/stubs.go +++ b/src/runtime/stubs.go @@ -73,7 +73,15 @@ func badsystemstack() { // *ptr is uninitialized memory (e.g., memory that's being reused // for a new allocation) and hence contains only "junk". // +// memclrNoHeapPointers ensures that if ptr is pointer-aligned, and n +// is a multiple of the pointer size, then any pointer-aligned, +// pointer-sized portion is cleared atomically. Despite the function +// name, this is necessary because this function is the underlying +// implementation of typedmemclr and memclrHasPointers. See the doc of +// memmove for more details. +// // The (CPU-specific) implementations of this function are in memclr_*.s. +// //go:noescape func memclrNoHeapPointers(ptr unsafe.Pointer, n uintptr) -- cgit v1.2.3-54-g00ecf From 44361140c02556a0a71bc52299149bb8de26024b Mon Sep 17 00:00:00 2001 From: Ian Lance Taylor Date: Fri, 29 Jan 2021 10:25:34 -0800 Subject: embed: update docs for proposal tweaks //go:embed variables can be type aliases. //go:embed variables can't be local to a function. For #43216 For #43602 Fixes #43978 Change-Id: Ib1d104dfa32b97c91d8bfc5ed5d461ca14da188f Reviewed-on: https://go-review.googlesource.com/c/go/+/288072 Trust: Ian Lance Taylor Reviewed-by: Russ Cox --- src/embed/embed.go | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/src/embed/embed.go b/src/embed/embed.go index cc6855e6a5..f12bf31e76 100644 --- a/src/embed/embed.go +++ b/src/embed/embed.go @@ -9,18 +9,28 @@ // files read from the package directory or subdirectories at compile time. // // For example, here are three ways to embed a file named hello.txt -// and then print its contents at run time: +// and then print its contents at run time. // -// import "embed" +// Embedding one file into a string: +// +// import _ "embed" // // //go:embed hello.txt // var s string // print(s) // +// Embedding one file into a slice of bytes: +// +// import _ "embed" +// // //go:embed hello.txt // var b []byte // print(string(b)) // +// Embedded one or more files into a file system: +// +// import "embed" +// // //go:embed hello.txt // var f embed.FS // data, _ := f.ReadFile("hello.txt") @@ -34,8 +44,8 @@ // The directive must immediately precede a line containing the declaration of a single variable. // Only blank lines and ‘//’ line comments are permitted between the directive and the declaration. // -// The variable must be of type string, []byte, or FS exactly. Named types or type aliases -// derived from those types are not allowed. +// The type of the variable must be a string type, or a slice of a byte type, +// or FS (or an alias of FS). // // For example: // @@ -70,8 +80,8 @@ // // The //go:embed directive can be used with both exported and unexported variables, // depending on whether the package wants to make the data available to other packages. -// Similarly, it can be used with both global and function-local variables, -// depending on what is more convenient in context. +// It can only be used with global variables at package scope, +// not with local variables. // // Patterns must not match files outside the package's module, such as ‘.git/*’ or symbolic links. // Matches for empty directories are ignored. After that, each pattern in a //go:embed line -- cgit v1.2.3-54-g00ecf From 6ac91e460c294bda5a50e628b7556bf20525fa44 Mon Sep 17 00:00:00 2001 From: Toshihiro Shiino Date: Sun, 31 Jan 2021 12:42:44 +0000 Subject: doc/go1.16: minor markup fixes Add missing tags. Remove unnecessary
tag. For #40700 Change-Id: I03d3ce1c89a9ae3d3195dcd2bb8b1a61f011e1ed Reviewed-on: https://go-review.googlesource.com/c/go/+/288275 Reviewed-by: Dmitri Shuralyov Reviewed-by: Ian Lance Taylor Reviewed-by: Alberto Donizetti --- doc/go1.16.html | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc/go1.16.html b/doc/go1.16.html index 6cc75b4865..fc01a5f509 100644 --- a/doc/go1.16.html +++ b/doc/go1.16.html @@ -146,7 +146,7 @@ Do not send CLs removing the interior tags from such phrases. retract directives may now be used in a go.mod file to indicate that certain published versions of the module should not be used by other modules. A module author may retract a version after a severe problem - is discovered or if the version was published unintentionally.
+ is discovered or if the version was published unintentionally.

@@ -899,7 +899,7 @@ func TestFoo(t *testing.T) {

- The Client now sends + The Client now sends an explicit Content-Length: 0 header in PATCH requests with empty bodies, matching the existing behavior of POST and PUT. @@ -946,7 +946,7 @@ func TestFoo(t *testing.T) {

net/smtp

- The Client's + The Client's Mail method now sends the SMTPUTF8 directive to servers that support it, signaling that addresses are encoded in UTF-8. -- cgit v1.2.3-54-g00ecf From 26e29aa15a189b26d3b2400a594d329368e78e79 Mon Sep 17 00:00:00 2001 From: Nehal J Wani Date: Tue, 26 Jan 2021 16:29:05 +0000 Subject: cmd/link: disable TestPIESize if CGO isn't enabled With CGO disabled, the test throws the following error: elf_test.go:291: # command-line-arguments loadinternal: cannot find runtime/cgo Change-Id: Iaeb183562ab637c714240b49e73078bdb791b35b GitHub-Last-Rev: f8fe9afad5611411966413d17cb5874f7b0018a0 GitHub-Pull-Request: golang/go#43911 Reviewed-on: https://go-review.googlesource.com/c/go/+/286632 Run-TryBot: Ian Lance Taylor TryBot-Result: Go Bot Reviewed-by: Ian Lance Taylor Reviewed-by: Cherry Zhang Trust: Matthew Dempsky --- src/cmd/link/elf_test.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/cmd/link/elf_test.go b/src/cmd/link/elf_test.go index 334f050e88..20754d09f5 100644 --- a/src/cmd/link/elf_test.go +++ b/src/cmd/link/elf_test.go @@ -226,6 +226,12 @@ func main() { func TestPIESize(t *testing.T) { testenv.MustHaveGoBuild(t) + + // We don't want to test -linkmode=external if cgo is not supported. + // On some systems -buildmode=pie implies -linkmode=external, so just + // always skip the test if cgo is not supported. + testenv.MustHaveCGO(t) + if !sys.BuildModeSupported(runtime.Compiler, "pie", runtime.GOOS, runtime.GOARCH) { t.Skip("-buildmode=pie not supported") } -- cgit v1.2.3-54-g00ecf From 0b6cfea6342a7d95f74bc9e273039236ebd7e64f Mon Sep 17 00:00:00 2001 From: Cherry Zhang Date: Thu, 28 Jan 2021 12:19:49 -0500 Subject: doc/go1.16: document that on OpenBSD syscalls are now made through libc Updates #36435, #40700. Change-Id: I1e2ded111ad58066cc9f2c9d00e719497b0f34d8 Reviewed-on: https://go-review.googlesource.com/c/go/+/287634 Trust: Cherry Zhang Reviewed-by: Joel Sing --- doc/go1.16.html | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/doc/go1.16.html b/doc/go1.16.html index fc01a5f509..8d31f63fa2 100644 --- a/doc/go1.16.html +++ b/doc/go1.16.html @@ -80,6 +80,16 @@ Do not send CLs removing the interior tags from such phrases. support cgo.

+

+ On the 64-bit x86 and 64-bit ARM architectures on OpenBSD (the + openbsd/amd64 and openbsd/arm64 ports), system + calls are now made through libc, instead of directly using + the SYSCALL/SVC instruction. This ensures + forward-compatibility with future versions of OpenBSD. In particular, + OpenBSD 6.9 onwards will require system calls to be made through + libc for non-static Go binaries. +

+

386

-- cgit v1.2.3-54-g00ecf From 32e789f4fb45b6296b9283ab80e126287eab4db5 Mon Sep 17 00:00:00 2001 From: Tom Thorogood Date: Mon, 1 Feb 2021 13:32:18 +1030 Subject: test: fix incorrectly laid out instructions in issue11656.go CL 279423 introduced a regression in this test as it incorrectly laid out various instructions. In the case of arm, the second instruction was overwriting the first. In the case of 386, amd64 and s390x, the instructions were being appended to the end of the slice after 64 zero bytes. This was causing test failures on "linux/s390x on z13". Fixes #44028 Change-Id: Id136212dabdae27db7e91904b0df6a3a9d2f4af4 Reviewed-on: https://go-review.googlesource.com/c/go/+/288278 Run-TryBot: Ian Lance Taylor Reviewed-by: Keith Randall Reviewed-by: Cherry Zhang --- test/fixedbugs/issue11656.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/fixedbugs/issue11656.go b/test/fixedbugs/issue11656.go index acd3f4f3e5..85fe720b30 100644 --- a/test/fixedbugs/issue11656.go +++ b/test/fixedbugs/issue11656.go @@ -59,10 +59,10 @@ func f(n int) { ill := make([]byte, 64) switch runtime.GOARCH { case "386", "amd64": - ill = append(ill, 0x89, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00) // MOVL AX, 0 + ill = append(ill[:0], 0x89, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00) // MOVL AX, 0 case "arm": - binary.LittleEndian.PutUint32(ill, 0xe3a00000) // MOVW $0, R0 - binary.LittleEndian.PutUint32(ill, 0xe5800000) // MOVW R0, (R0) + binary.LittleEndian.PutUint32(ill[0:4], 0xe3a00000) // MOVW $0, R0 + binary.LittleEndian.PutUint32(ill[4:8], 0xe5800000) // MOVW R0, (R0) case "arm64": binary.LittleEndian.PutUint32(ill, 0xf90003ff) // MOVD ZR, (ZR) case "ppc64": @@ -74,7 +74,7 @@ func f(n int) { case "mipsle", "mips64le": binary.LittleEndian.PutUint32(ill, 0xfc000000) // MOVV R0, (R0) case "s390x": - ill = append(ill, 0xa7, 0x09, 0x00, 0x00) // MOVD $0, R0 + ill = append(ill[:0], 0xa7, 0x09, 0x00, 0x00) // MOVD $0, R0 ill = append(ill, 0xe3, 0x00, 0x00, 0x00, 0x00, 0x24) // MOVD R0, (R0) case "riscv64": binary.LittleEndian.PutUint32(ill, 0x00003023) // MOV X0, (X0) -- cgit v1.2.3-54-g00ecf From 1426a571b79bfcb3c0339e2fd96c893cd1549af6 Mon Sep 17 00:00:00 2001 From: Cherry Zhang Date: Mon, 1 Feb 2021 16:46:49 -0500 Subject: cmd/link: fix off-by-1 error in findShlibSection We want to find a section that contains addr. sect.Addr+sect.Size is the exclusive upper bound. Change-Id: If2cd6bdd6e03174680e066189b0f4bf9e2ba6630 Reviewed-on: https://go-review.googlesource.com/c/go/+/288592 Trust: Cherry Zhang Run-TryBot: Cherry Zhang TryBot-Result: Go Bot Reviewed-by: Than McIntosh --- src/cmd/link/internal/ld/decodesym.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cmd/link/internal/ld/decodesym.go b/src/cmd/link/internal/ld/decodesym.go index c6e2d8ca7f..fc179fc6e4 100644 --- a/src/cmd/link/internal/ld/decodesym.go +++ b/src/cmd/link/internal/ld/decodesym.go @@ -279,7 +279,7 @@ func findShlibSection(ctxt *Link, path string, addr uint64) *elf.Section { for _, shlib := range ctxt.Shlibs { if shlib.Path == path { for _, sect := range shlib.File.Sections[1:] { // skip the NULL section - if sect.Addr <= addr && addr <= sect.Addr+sect.Size { + if sect.Addr <= addr && addr < sect.Addr+sect.Size { return sect } } -- cgit v1.2.3-54-g00ecf From 98f8454a73b569d81d1c5e167d7b68f22e2e3fea Mon Sep 17 00:00:00 2001 From: Cherry Zhang Date: Mon, 1 Feb 2021 13:36:50 -0500 Subject: cmd/link: don't decode type symbol in shared library in deadcode In the linker's deadcode pass we decode type symbols for interface satisfaction analysis. When linking against Go shared libraries, the type symbol may come from a shared library, so it doesn't have data in the current module being linked, so we cannot decode it. We already have code to skip DYNIMPORT symbols. However, this doesn't actually work, because at that point the type symbols' names haven't been mangled, whereas they may be mangled in the shared library. So the symbol definition (in shared library) and reference (in current module) haven't been connected. Skip decoding type symbols of type Sxxx (along with DYNIMPORT) when linkShared. Note: we cannot skip all type symbols, as we still need to mark unexported methods defined in the current module. Fixes #44031. Change-Id: I833d19a060c94edbd6fc448172358f9a7d760657 Reviewed-on: https://go-review.googlesource.com/c/go/+/288496 Trust: Cherry Zhang Trust: Than McIntosh Run-TryBot: Cherry Zhang TryBot-Result: Go Bot Reviewed-by: Than McIntosh --- misc/cgo/testshared/shared_test.go | 8 ++++++++ misc/cgo/testshared/testdata/issue44031/a/a.go | 9 +++++++++ misc/cgo/testshared/testdata/issue44031/b/b.go | 17 +++++++++++++++++ misc/cgo/testshared/testdata/issue44031/main/main.go | 20 ++++++++++++++++++++ src/cmd/link/internal/ld/deadcode.go | 16 ++++++++++------ 5 files changed, 64 insertions(+), 6 deletions(-) create mode 100644 misc/cgo/testshared/testdata/issue44031/a/a.go create mode 100644 misc/cgo/testshared/testdata/issue44031/b/b.go create mode 100644 misc/cgo/testshared/testdata/issue44031/main/main.go diff --git a/misc/cgo/testshared/shared_test.go b/misc/cgo/testshared/shared_test.go index 5e0893784b..f52391c6f6 100644 --- a/misc/cgo/testshared/shared_test.go +++ b/misc/cgo/testshared/shared_test.go @@ -1063,3 +1063,11 @@ func TestGCData(t *testing.T) { goCmd(t, "build", "-linkshared", "./gcdata/main") runWithEnv(t, "running gcdata/main", []string{"GODEBUG=clobberfree=1"}, "./main") } + +// Test that we don't decode type symbols from shared libraries (which has no data, +// causing panic). See issue 44031. +func TestIssue44031(t *testing.T) { + goCmd(t, "install", "-buildmode=shared", "-linkshared", "./issue44031/a") + goCmd(t, "install", "-buildmode=shared", "-linkshared", "./issue44031/b") + goCmd(t, "run", "-linkshared", "./issue44031/main") +} diff --git a/misc/cgo/testshared/testdata/issue44031/a/a.go b/misc/cgo/testshared/testdata/issue44031/a/a.go new file mode 100644 index 0000000000..48827e682f --- /dev/null +++ b/misc/cgo/testshared/testdata/issue44031/a/a.go @@ -0,0 +1,9 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package a + +type ATypeWithALoooooongName interface { // a long name, so the type descriptor symbol name is mangled + M() +} diff --git a/misc/cgo/testshared/testdata/issue44031/b/b.go b/misc/cgo/testshared/testdata/issue44031/b/b.go new file mode 100644 index 0000000000..ad3ebec2b9 --- /dev/null +++ b/misc/cgo/testshared/testdata/issue44031/b/b.go @@ -0,0 +1,17 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package b + +import "testshared/issue44031/a" + +type T int + +func (T) M() {} + +var i = a.ATypeWithALoooooongName(T(0)) + +func F() { + i.M() +} diff --git a/misc/cgo/testshared/testdata/issue44031/main/main.go b/misc/cgo/testshared/testdata/issue44031/main/main.go new file mode 100644 index 0000000000..47f2e3a98e --- /dev/null +++ b/misc/cgo/testshared/testdata/issue44031/main/main.go @@ -0,0 +1,20 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import "testshared/issue44031/b" + +type t int + +func (t) m() {} + +type i interface{ m() } // test that unexported method is correctly marked + +var v interface{} = t(0) + +func main() { + b.F() + v.(i).m() +} diff --git a/src/cmd/link/internal/ld/deadcode.go b/src/cmd/link/internal/ld/deadcode.go index d8813fa936..245076a83a 100644 --- a/src/cmd/link/internal/ld/deadcode.go +++ b/src/cmd/link/internal/ld/deadcode.go @@ -165,13 +165,17 @@ func (d *deadcodePass) flood() { // R_USEIFACEMETHOD is a marker relocation that marks an interface // method as used. rs := r.Sym() - if d.ldr.SymType(rs) != sym.SDYNIMPORT { // don't decode DYNIMPORT symbol (we'll mark all exported methods anyway) - m := d.decodeIfaceMethod(d.ldr, d.ctxt.Arch, rs, r.Add()) - if d.ctxt.Debugvlog > 1 { - d.ctxt.Logf("reached iface method: %v\n", m) - } - d.ifaceMethod[m] = true + if d.ctxt.linkShared && (d.ldr.SymType(rs) == sym.SDYNIMPORT || d.ldr.SymType(rs) == sym.Sxxx) { + // Don't decode symbol from shared library (we'll mark all exported methods anyway). + // We check for both SDYNIMPORT and Sxxx because name-mangled symbols haven't + // been resolved at this point. + continue + } + m := d.decodeIfaceMethod(d.ldr, d.ctxt.Arch, rs, r.Add()) + if d.ctxt.Debugvlog > 1 { + d.ctxt.Logf("reached iface method: %v\n", m) } + d.ifaceMethod[m] = true continue } rs := r.Sym() -- cgit v1.2.3-54-g00ecf From fca94ab3ab113ceddb7934f76d0f1660cad98260 Mon Sep 17 00:00:00 2001 From: task4233 Date: Tue, 2 Feb 2021 03:54:24 +0000 Subject: spec: improve the example in Type assertions section The example, var v, ok T1 = x.(T), can be interpreted as type T1 interface{} or type T = bool; type T1 = T. Separating the example would help understanding for readers. Change-Id: I179f4564e67f4d503815d29307df2cebb50c82f9 GitHub-Last-Rev: b34fffb6bb07cb2883bc313ef3bc9980b3dd4abe GitHub-Pull-Request: golang/go#44040 Reviewed-on: https://go-review.googlesource.com/c/go/+/288472 Reviewed-by: Robert Griesemer Reviewed-by: Rob Pike Reviewed-by: Ian Lance Taylor Trust: Robert Griesemer --- doc/go_spec.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/go_spec.html b/doc/go_spec.html index 676407f6f2..c9e14a3fec 100644 --- a/doc/go_spec.html +++ b/doc/go_spec.html @@ -1,6 +1,6 @@ @@ -3400,7 +3400,7 @@ A type assertion used in an assignment or initializat v, ok = x.(T) v, ok := x.(T) var v, ok = x.(T) -var v, ok T1 = x.(T) +var v, ok interface{} = x.(T) // dynamic types of v and ok are T and bool

-- cgit v1.2.3-54-g00ecf From e491c6eea9ad599a0ae766a3217bd9a16ca3a25a Mon Sep 17 00:00:00 2001 From: Katie Hockman Date: Wed, 27 Jan 2021 10:33:35 -0500 Subject: math/big: fix comment in divRecursiveStep There appears to be a typo in the description of the recursive division algorithm. Two things seem suspicious with the original comment: 1. It is talking about choosing s, but s doesn't appear anywhere in the equation. 2. The math in the equation is incorrect. Where B = len(v)/2 s = B - 1 Proof that it is incorrect: len(v) - B >= B + 1 len(v) - len(v)/2 >= len(v)/2 + 1 This doesn't hold if len(v) is even, e.g. 10: 10 - 10/2 >= 10/2 + 1 10 - 5 >= 5 + 1 5 >= 6 // this is false The new equation will be the following, which will be mathematically correct: len(v) - s >= B + 1 len(v) - (len(v)/2 - 1) >= len(v)/2 + 1 len(v) - len(v)/2 + 1 >= len(v)/2 + 1 len(v) - len(v)/2 >= len(v)/2 This holds if len(v) is even or odd. e.g. 10 10 - 10/2 >= 10/2 10 - 5 >= 5 5 >= 5 e.g. 11 11 - 11/2 >= 11/2 11 - 5 >= 5 6 >= 5 Change-Id: If77ce09286cf7038637b5dfd0fb7d4f828023f56 Reviewed-on: https://go-review.googlesource.com/c/go/+/287372 Run-TryBot: Katie Hockman Reviewed-by: Filippo Valsorda Trust: Katie Hockman --- src/math/big/nat.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/math/big/nat.go b/src/math/big/nat.go index 068176e1c1..bbd6c8850b 100644 --- a/src/math/big/nat.go +++ b/src/math/big/nat.go @@ -881,7 +881,7 @@ func (z nat) divRecursiveStep(u, v nat, depth int, tmp *nat, temps []*nat) { // then floor(u1/v1) >= floor(u/v) // // Moreover, the difference is at most 2 if len(v1) >= len(u/v) - // We choose s = B-1 since len(v)-B >= B+1 >= len(u/v) + // We choose s = B-1 since len(v)-s >= B+1 >= len(u/v) s := (B - 1) // Except for the first step, the top bits are always // a division remainder, so the quotient length is <= n. -- cgit v1.2.3-54-g00ecf From 8869086d8f0a31033ccdc103106c768dc17216b1 Mon Sep 17 00:00:00 2001 From: Ikko Ashimine Date: Thu, 4 Feb 2021 02:47:37 +0000 Subject: runtime: fix typo in histogram.go indicies -> indices Change-Id: Ia50ae5918fc7a53c23590a94a18087a99bfd9bb7 GitHub-Last-Rev: 98eb724275fd61d5f5ce5dad6b1010c10f76906d GitHub-Pull-Request: golang/go#44095 Reviewed-on: https://go-review.googlesource.com/c/go/+/289529 Reviewed-by: Ian Lance Taylor Trust: Keith Randall --- src/runtime/histogram.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/runtime/histogram.go b/src/runtime/histogram.go index 42baa6c5e2..da4910d341 100644 --- a/src/runtime/histogram.go +++ b/src/runtime/histogram.go @@ -26,7 +26,7 @@ const ( // The number of super-buckets (timeHistNumSuperBuckets), on the // other hand, defines the range. To reserve room for sub-buckets, // bit timeHistSubBucketBits is the first bit considered for - // super-buckets, so super-bucket indicies are adjusted accordingly. + // super-buckets, so super-bucket indices are adjusted accordingly. // // As an example, consider 45 super-buckets with 16 sub-buckets. // -- cgit v1.2.3-54-g00ecf From 4516afebedd18692c6dc70cbdee16a049c26024b Mon Sep 17 00:00:00 2001 From: Russ Cox Date: Fri, 5 Feb 2021 10:55:12 -0500 Subject: testing/fstest: avoid symlink-induced failures in tester Do not require directory entry and Stat result to match for symlinks, because they won't (Stat dereferences the symlink). Fixes #44113. Change-Id: Ifc6dbce5719906e2f42254a7172f1ef787464a9e Reviewed-on: https://go-review.googlesource.com/c/go/+/290009 Trust: Russ Cox Run-TryBot: Russ Cox Reviewed-by: Bryan C. Mills --- src/testing/fstest/testfs.go | 25 ++++++++++++++++++------- src/testing/fstest/testfs_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 7 deletions(-) create mode 100644 src/testing/fstest/testfs_test.go diff --git a/src/testing/fstest/testfs.go b/src/testing/fstest/testfs.go index a7f8007333..8fc8acaaf3 100644 --- a/src/testing/fstest/testfs.go +++ b/src/testing/fstest/testfs.go @@ -403,9 +403,10 @@ func (t *fsTester) checkStat(path string, entry fs.DirEntry) { return } fentry := formatEntry(entry) - finfo := formatInfoEntry(info) - if fentry != finfo { - t.errorf("%s: mismatch:\n\tentry = %s\n\tfile.Stat() = %s", path, fentry, finfo) + fientry := formatInfoEntry(info) + // Note: mismatch here is OK for symlink, because Open dereferences symlink. + if fentry != fientry && entry.Type()&fs.ModeSymlink == 0 { + t.errorf("%s: mismatch:\n\tentry = %s\n\tfile.Stat() = %s", path, fentry, fientry) } einfo, err := entry.Info() @@ -413,12 +414,22 @@ func (t *fsTester) checkStat(path string, entry fs.DirEntry) { t.errorf("%s: entry.Info: %v", path, err) return } - fentry = formatInfo(einfo) - finfo = formatInfo(info) - if fentry != finfo { - t.errorf("%s: mismatch:\n\tentry.Info() = %s\n\tfile.Stat() = %s\n", path, fentry, finfo) + finfo := formatInfo(info) + if entry.Type()&fs.ModeSymlink != 0 { + // For symlink, just check that entry.Info matches entry on common fields. + // Open deferences symlink, so info itself may differ. + feentry := formatInfoEntry(einfo) + if fentry != feentry { + t.errorf("%s: mismatch\n\tentry = %s\n\tentry.Info() = %s\n", path, fentry, feentry) + } + } else { + feinfo := formatInfo(einfo) + if feinfo != finfo { + t.errorf("%s: mismatch:\n\tentry.Info() = %s\n\tfile.Stat() = %s\n", path, feinfo, finfo) + } } + // Stat should be the same as Open+Stat, even for symlinks. info2, err := fs.Stat(t.fsys, path) if err != nil { t.errorf("%s: fs.Stat: %v", path, err) diff --git a/src/testing/fstest/testfs_test.go b/src/testing/fstest/testfs_test.go new file mode 100644 index 0000000000..5b8813c343 --- /dev/null +++ b/src/testing/fstest/testfs_test.go @@ -0,0 +1,31 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package fstest + +import ( + "internal/testenv" + "os" + "path/filepath" + "testing" +) + +func TestSymlink(t *testing.T) { + testenv.MustHaveSymlink(t) + + tmp := t.TempDir() + tmpfs := os.DirFS(tmp) + + if err := os.WriteFile(filepath.Join(tmp, "hello"), []byte("hello, world\n"), 0644); err != nil { + t.Fatal(err) + } + + if err := os.Symlink(filepath.Join(tmp, "hello"), filepath.Join(tmp, "hello.link")); err != nil { + t.Fatal(err) + } + + if err := TestFS(tmpfs, "hello", "hello.link"); err != nil { + t.Fatal(err) + } +} -- cgit v1.2.3-54-g00ecf From b54cd94d478c95e79e5eea1d77e73d7b2b769f09 Mon Sep 17 00:00:00 2001 From: Jay Conrod Date: Fri, 5 Feb 2021 16:45:40 -0500 Subject: embed, io/fs: clarify that leading and trailing slashes are disallowed Fixes #44012 Change-Id: I5782cea301a65ae12ba870ff1e6b2e0a2651dc09 Reviewed-on: https://go-review.googlesource.com/c/go/+/290071 Run-TryBot: Jay Conrod Reviewed-by: Bryan C. Mills TryBot-Result: Go Bot Trust: Jay Conrod --- src/embed/embed.go | 18 +++++++++--------- src/io/fs/fs.go | 1 + 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/src/embed/embed.go b/src/embed/embed.go index f12bf31e76..98da870ac6 100644 --- a/src/embed/embed.go +++ b/src/embed/embed.go @@ -61,12 +61,15 @@ // The Go build system will recognize the directives and arrange for the declared variable // (in the example above, content) to be populated with the matching files from the file system. // -// The //go:embed directive accepts multiple space-separated patterns for brevity, -// but it can also be repeated, to avoid very long lines when there are many patterns. -// The patterns are interpreted relative to the package directory containing the source file. -// The path separator is a forward slash, even on Windows systems. -// To allow for naming files with spaces in their names, patterns can be written -// as Go double-quoted or back-quoted string literals. +// The //go:embed directive accepts multiple space-separated patterns for +// brevity, but it can also be repeated, to avoid very long lines when there are +// many patterns. The patterns are interpreted relative to the package directory +// containing the source file. The path separator is a forward slash, even on +// Windows systems. Patterns may not contain ‘.’ or ‘..’ or empty path elements, +// nor may they begin or end with a slash. To match everything in the current +// directory, use ‘*’ instead of ‘.’. To allow for naming files with spaces in +// their names, patterns can be written as Go double-quoted or back-quoted +// string literals. // // If a pattern names a directory, all files in the subtree rooted at that directory are // embedded (recursively), except that files with names beginning with ‘.’ or ‘_’ @@ -87,9 +90,6 @@ // Matches for empty directories are ignored. After that, each pattern in a //go:embed line // must match at least one file or non-empty directory. // -// Patterns must not contain ‘.’ or ‘..’ path elements nor begin with a leading slash. -// To match everything in the current directory, use ‘*’ instead of ‘.’. -// // If any patterns are invalid or have invalid matches, the build will fail. // // Strings and Bytes diff --git a/src/io/fs/fs.go b/src/io/fs/fs.go index b691a86049..c330f123ad 100644 --- a/src/io/fs/fs.go +++ b/src/io/fs/fs.go @@ -36,6 +36,7 @@ type FS interface { // sequences of path elements, like “x/y/z”. // Path names must not contain a “.” or “..” or empty element, // except for the special case that the root directory is named “.”. +// Leading and trailing slashes (like “/x” or “x/”) are not allowed. // // Paths are slash-separated on all systems, even Windows. // Backslashes must not appear in path names. -- cgit v1.2.3-54-g00ecf From 724d0720b3e110f64598bf789cbe2a6a1b3b0fd8 Mon Sep 17 00:00:00 2001 From: KimMachineGun Date: Fri, 5 Feb 2021 05:47:46 +0000 Subject: doc/go1.16: add missed heading tag in vet section Add missed heading tag in CL 276373. For #40700 Change-Id: Ida9e8861589bbc296a5a1cecbf9fe33fa09ed0ca GitHub-Last-Rev: d218f8d4b70b20c30422863db7bed3683e3218e6 GitHub-Pull-Request: golang/go#44111 Reviewed-on: https://go-review.googlesource.com/c/go/+/289869 Reviewed-by: Tim King Reviewed-by: Dmitri Shuralyov Trust: Tim King Trust: Dmitri Shuralyov --- doc/go1.16.html | 2 ++ 1 file changed, 2 insertions(+) diff --git a/doc/go1.16.html b/doc/go1.16.html index 8d31f63fa2..878bf0d029 100644 --- a/doc/go1.16.html +++ b/doc/go1.16.html @@ -364,6 +364,8 @@ func TestFoo(t *testing.T) { } +

New warning for frame pointer

+

The vet tool now warns about amd64 assembly that clobbers the BP register (the frame pointer) without saving and restoring it, -- cgit v1.2.3-54-g00ecf From ed3e4afa12d655a0c5606bcf3dd4e1cdadcb1476 Mon Sep 17 00:00:00 2001 From: Ori Bernstein Date: Wed, 6 Jan 2021 02:40:05 +0000 Subject: syscall/plan9: remove spooky fd action at a distance Change Plan 9 fork/exec to use the O_CLOEXEC file descriptor, instead of relying on spooky at a distance. Historically, Plan 9 has set the O_CLOEXEC flag on the underlying channels in the kernel, rather than the file descriptors -- if two fds pointed at a single channel, as with dup, changing the flags on one of them would be observable on the other. The per-Chan semantics are ok, if unexpected, when a chan is only handled within a single process, but this isn't always the case. Forked processes share Chans, but even more of a problem is the interaction between /srv and OCEXEC, which can lead to unexectedly closed file descriptors in completely unrelated proceses. For example: func exists() bool { // If some other thread execs here, // we don't want to leak the fd, so // open it O_CLOEXEC fd := Open("/srv/foo", O_CLOEXEC) if fd != -1 { Close(fd) return true } return false } would close the connection to any file descriptor (maybe even for the root fs) in ALL other processes that have it open if an exec were to happen(!), which is quite undesriable. As a result, 9front will be changing this behavior for the next release. Go is the only code observed so far that relies on this behavior on purpose, and It's easy to make the code work with both semantics: simply using the file descriptor that was opened with O_CEXEC instead of throwing it away. So we do that here. Fixes #43524 Change-Id: I4887f5c934a5e63e5e6c1bb59878a325abc928d3 GitHub-Last-Rev: 96bb21bd1e8f64dc7e082a56928748a7d54c9272 GitHub-Pull-Request: golang/go#43533 Reviewed-on: https://go-review.googlesource.com/c/go/+/281833 Reviewed-by: David du Colombier <0intro@gmail.com> Reviewed-by: Richard Miller Reviewed-by: Jacob Moody Run-TryBot: David du Colombier <0intro@gmail.com> Trust: Ian Lance Taylor --- src/syscall/exec_plan9.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/syscall/exec_plan9.go b/src/syscall/exec_plan9.go index 47ccbdc384..12c4237f69 100644 --- a/src/syscall/exec_plan9.go +++ b/src/syscall/exec_plan9.go @@ -320,14 +320,15 @@ func cexecPipe(p []int) error { return e } - fd, e := Open("#d/"+itoa(p[1]), O_CLOEXEC) + fd, e := Open("#d/"+itoa(p[1]), O_RDWR|O_CLOEXEC) if e != nil { Close(p[0]) Close(p[1]) return e } - Close(fd) + Close(p[1]) + p[1] = fd return nil } -- cgit v1.2.3-54-g00ecf From 1901853098bbe25a1bbedc0ee53c6658d754151e Mon Sep 17 00:00:00 2001 From: Changkun Ou Date: Sun, 7 Feb 2021 17:31:12 +0100 Subject: runtime/metrics: fix panic in readingAllMetric example medianBucket can return if the total is greater than thresh. However, if a histogram has no counts, total and thresh will both be zero and cause panic. Adding an equal sign to prevent the potential panic. Fixes #44148 Change-Id: Ifb8a781990f490d142ae7c035b4e01d6a07ae04d Reviewed-on: https://go-review.googlesource.com/c/go/+/290171 Trust: Ian Lance Taylor Reviewed-by: Michael Knyszek Run-TryBot: Michael Knyszek TryBot-Result: Go Bot --- src/runtime/metrics/example_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/runtime/metrics/example_test.go b/src/runtime/metrics/example_test.go index cade0c38bf..624d9d8a6b 100644 --- a/src/runtime/metrics/example_test.go +++ b/src/runtime/metrics/example_test.go @@ -88,7 +88,7 @@ func medianBucket(h *metrics.Float64Histogram) float64 { total = 0 for i, count := range h.Counts { total += count - if total > thresh { + if total >= thresh { return h.Buckets[i] } } -- cgit v1.2.3-54-g00ecf From dc725bfb3c3f29c7395e088d25ef6bf8dba8f129 Mon Sep 17 00:00:00 2001 From: KimMachineGun Date: Mon, 8 Feb 2021 23:27:52 +0000 Subject: doc/go1.16: mention new vet check for asn1.Unmarshal This vet check was added in CL 243397. For #40700. Change-Id: Ibff6df9395d37bb2b84a791443578009f23af4fb GitHub-Last-Rev: e47c38f6309f31a6de48d4ffc82078d7ad45b171 GitHub-Pull-Request: golang/go#44147 Reviewed-on: https://go-review.googlesource.com/c/go/+/290330 Trust: Ian Lance Taylor Reviewed-by: Dmitri Shuralyov --- doc/go1.16.html | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/doc/go1.16.html b/doc/go1.16.html index 878bf0d029..f6f72c3882 100644 --- a/doc/go1.16.html +++ b/doc/go1.16.html @@ -378,6 +378,16 @@ func TestFoo(t *testing.T) { fixes.

+

New warning for asn1.Unmarshal

+ +

+ The vet tool now warns about incorrectly passing a non-pointer or nil argument to + asn1.Unmarshal. + This is like the existing checks for + encoding/json.Unmarshal + and encoding/xml.Unmarshal. +

+

Runtime

-- cgit v1.2.3-54-g00ecf From cea4e21b525ad6b465f62741680eaa0a44e9cc3e Mon Sep 17 00:00:00 2001 From: Ian Lance Taylor Date: Mon, 8 Feb 2021 16:32:39 -0800 Subject: io/fs: backslash is always a glob meta character Fixes #44171 Change-Id: I2d3437a2f5b9fa0358e4664e1a8eacebed975eed Reviewed-on: https://go-review.googlesource.com/c/go/+/290512 Trust: Ian Lance Taylor Run-TryBot: Ian Lance Taylor TryBot-Result: Go Bot Reviewed-by: Rob Pike Reviewed-by: Russ Cox --- src/io/fs/glob.go | 5 ++--- src/io/fs/glob_test.go | 3 ++- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/io/fs/glob.go b/src/io/fs/glob.go index 549f217542..45d9cb61b9 100644 --- a/src/io/fs/glob.go +++ b/src/io/fs/glob.go @@ -6,7 +6,6 @@ package fs import ( "path" - "runtime" ) // A GlobFS is a file system with a Glob method. @@ -111,8 +110,8 @@ func glob(fs FS, dir, pattern string, matches []string) (m []string, e error) { // recognized by path.Match. func hasMeta(path string) bool { for i := 0; i < len(path); i++ { - c := path[i] - if c == '*' || c == '?' || c == '[' || runtime.GOOS == "windows" && c == '\\' { + switch path[i] { + case '*', '?', '[', '\\': return true } } diff --git a/src/io/fs/glob_test.go b/src/io/fs/glob_test.go index f0d791fab5..f19bebed77 100644 --- a/src/io/fs/glob_test.go +++ b/src/io/fs/glob_test.go @@ -17,6 +17,7 @@ var globTests = []struct { }{ {os.DirFS("."), "glob.go", "glob.go"}, {os.DirFS("."), "gl?b.go", "glob.go"}, + {os.DirFS("."), `gl\ob.go`, "glob.go"}, {os.DirFS("."), "*", "glob.go"}, {os.DirFS(".."), "*/glob.go", "fs/glob.go"}, } @@ -32,7 +33,7 @@ func TestGlob(t *testing.T) { t.Errorf("Glob(%#q) = %#v want %v", tt.pattern, matches, tt.result) } } - for _, pattern := range []string{"no_match", "../*/no_match"} { + for _, pattern := range []string{"no_match", "../*/no_match", `\*`} { matches, err := Glob(os.DirFS("."), pattern) if err != nil { t.Errorf("Glob error for %q: %s", pattern, err) -- cgit v1.2.3-54-g00ecf From c9d6f45fec19a9cb66ddd89d61bfa982f5bf4afe Mon Sep 17 00:00:00 2001 From: Ian Lance Taylor Date: Sun, 7 Feb 2021 15:25:39 -0800 Subject: runtime/metrics: fix a couple of documentation typpos Fixes #44150 Change-Id: Ibe5bfba01491dd8c2f0696fab40a1673230d76e9 Reviewed-on: https://go-review.googlesource.com/c/go/+/290349 Trust: Ian Lance Taylor Run-TryBot: Ian Lance Taylor TryBot-Result: Go Bot Reviewed-by: Dmitri Shuralyov Reviewed-by: Michael Knyszek --- src/runtime/metrics/doc.go | 7 ++++--- src/runtime/metrics/sample.go | 6 +++--- src/runtime/metrics/value.go | 2 +- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/runtime/metrics/doc.go b/src/runtime/metrics/doc.go index 021a0bddca..5da050f973 100644 --- a/src/runtime/metrics/doc.go +++ b/src/runtime/metrics/doc.go @@ -16,13 +16,14 @@ Interface Metrics are designated by a string key, rather than, for example, a field name in a struct. The full list of supported metrics is always available in the slice of Descriptions returned by All. Each Description also includes useful information -about the metric, such as how to display it (e.g. gauge vs. counter) and how difficult -or disruptive it is to obtain it (e.g. do you need to stop the world?). +about the metric, such as how to display it (for example, gauge vs. counter) +and how difficult or disruptive it is to obtain it (for example, do you need to +stop the world?). Thus, users of this API are encouraged to sample supported metrics defined by the slice returned by All to remain compatible across Go versions. Of course, situations arise where reading specific metrics is critical. For these cases, users are -encouranged to use build tags, and although metrics may be deprecated and removed, +encouraged to use build tags, and although metrics may be deprecated and removed, users should consider this to be an exceptional and rare event, coinciding with a very large change in a particular Go implementation. diff --git a/src/runtime/metrics/sample.go b/src/runtime/metrics/sample.go index 35534dd70d..b3933e266e 100644 --- a/src/runtime/metrics/sample.go +++ b/src/runtime/metrics/sample.go @@ -32,9 +32,9 @@ func runtime_readMetrics(unsafe.Pointer, int, int) // // Note that re-use has some caveats. Notably, Values should not be read or // manipulated while a Read with that value is outstanding; that is a data race. -// This property includes pointer-typed Values (e.g. Float64Histogram) whose -// underlying storage will be reused by Read when possible. To safely use such -// values in a concurrent setting, all data must be deep-copied. +// This property includes pointer-typed Values (for example, Float64Histogram) +// whose underlying storage will be reused by Read when possible. To safely use +// such values in a concurrent setting, all data must be deep-copied. // // It is safe to execute multiple Read calls concurrently, but their arguments // must share no underlying memory. When in doubt, create a new []Sample from diff --git a/src/runtime/metrics/value.go b/src/runtime/metrics/value.go index 61e8a192a3..ed9a33d87c 100644 --- a/src/runtime/metrics/value.go +++ b/src/runtime/metrics/value.go @@ -33,7 +33,7 @@ type Value struct { pointer unsafe.Pointer // contains non-scalar values. } -// Kind returns the a tag representing the kind of value this is. +// Kind returns the tag representing the kind of value this is. func (v Value) Kind() ValueKind { return v.kind } -- cgit v1.2.3-54-g00ecf From e0ac989cf3e43ec77c7205a66cb1cd63dd4d3043 Mon Sep 17 00:00:00 2001 From: Emmanuel T Odeke Date: Thu, 4 Feb 2021 01:39:18 -0800 Subject: archive/tar: detect out of bounds accesses in PAX records resulting from padded lengths Handles the case in which padding of a PAX record's length field violates invariants about the formatting of record, whereby it no longer matches the prescribed format: "%d %s=%s\n", , , as per: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html#tag_20_92_13_03 0-padding, and paddings of other sorts weren't handled and we assumed that only non-padded decimal lengths would be passed in. Added test cases to ensure that the parsing still proceeds as expected. The prior crashing repro: 0000000000000000000000000000000030 mtime=1432668921.098285006\n30 ctime=2147483649.15163319 exposed the fallacy in the code, that assumed that the length would ALWAYS be a non-padded decimal length string. This bug has existed since Go1.1 as per CL 6700047. Thanks to Josh Bleecher Snyder for fuzzing this package, and thanks to Tom Thorogood for advocacy, raising parity with GNU Tar, but for providing more test cases. Fixes #40196 Change-Id: I32e0af4887bc9221481bd9e8a5120a79f177f08c Reviewed-on: https://go-review.googlesource.com/c/go/+/289629 Trust: Emmanuel Odeke Trust: Joe Tsai Run-TryBot: Emmanuel Odeke TryBot-Result: Go Bot Reviewed-by: Joe Tsai --- src/archive/tar/strconv.go | 21 ++++++++++++++++++++- src/archive/tar/strconv_test.go | 7 +++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/archive/tar/strconv.go b/src/archive/tar/strconv.go index 6d0a403808..f0b61e6dba 100644 --- a/src/archive/tar/strconv.go +++ b/src/archive/tar/strconv.go @@ -265,8 +265,27 @@ func parsePAXRecord(s string) (k, v, r string, err error) { return "", "", s, ErrHeader } + afterSpace := int64(sp + 1) + beforeLastNewLine := n - 1 + // In some cases, "length" was perhaps padded/malformed, and + // trying to index past where the space supposedly is goes past + // the end of the actual record. + // For example: + // "0000000000000000000000000000000030 mtime=1432668921.098285006\n30 ctime=2147483649.15163319" + // ^ ^ + // | | + // | afterSpace=35 + // | + // beforeLastNewLine=29 + // yet indexOf(firstSpace) MUST BE before endOfRecord. + // + // See https://golang.org/issues/40196. + if afterSpace >= beforeLastNewLine { + return "", "", s, ErrHeader + } + // Extract everything between the space and the final newline. - rec, nl, rem := s[sp+1:n-1], s[n-1:n], s[n:] + rec, nl, rem := s[afterSpace:beforeLastNewLine], s[beforeLastNewLine:n], s[n:] if nl != "\n" { return "", "", s, ErrHeader } diff --git a/src/archive/tar/strconv_test.go b/src/archive/tar/strconv_test.go index dd3505a758..add65e272a 100644 --- a/src/archive/tar/strconv_test.go +++ b/src/archive/tar/strconv_test.go @@ -368,6 +368,13 @@ func TestParsePAXRecord(t *testing.T) { {"16 longkeyname=hahaha\n", "16 longkeyname=hahaha\n", "", "", false}, {"3 somelongkey=\n", "3 somelongkey=\n", "", "", false}, {"50 tooshort=\n", "50 tooshort=\n", "", "", false}, + {"0000000000000000000000000000000030 mtime=1432668921.098285006\n30 ctime=2147483649.15163319", "0000000000000000000000000000000030 mtime=1432668921.098285006\n30 ctime=2147483649.15163319", "mtime", "1432668921.098285006", false}, + {"06 k=v\n", "06 k=v\n", "", "", false}, + {"00006 k=v\n", "00006 k=v\n", "", "", false}, + {"000006 k=v\n", "000006 k=v\n", "", "", false}, + {"000000 k=v\n", "000000 k=v\n", "", "", false}, + {"0 k=v\n", "0 k=v\n", "", "", false}, + {"+0000005 x=\n", "+0000005 x=\n", "", "", false}, } for _, v := range vectors { -- cgit v1.2.3-54-g00ecf From e9c96835971044aa4ace37c7787de231bbde05d9 Mon Sep 17 00:00:00 2001 From: "Bryan C. Mills" Date: Thu, 4 Feb 2021 15:26:52 -0500 Subject: cmd/go: suppress errors from 'go get -d' for packages that only conditionally exist Fixes #44106 Fixes #29268 Change-Id: Id113f2ced274d43fbf66cb804581448218996f81 Reviewed-on: https://go-review.googlesource.com/c/go/+/289769 TryBot-Result: Go Bot Reviewed-by: Jay Conrod Trust: Bryan C. Mills Run-TryBot: Bryan C. Mills --- src/cmd/go/internal/modget/get.go | 20 +++-- src/cmd/go/testdata/script/mod_get_pkgtags.txt | 116 +++++++++++++++++++++++++ 2 files changed, 131 insertions(+), 5 deletions(-) create mode 100644 src/cmd/go/testdata/script/mod_get_pkgtags.txt diff --git a/src/cmd/go/internal/modget/get.go b/src/cmd/go/internal/modget/get.go index 574f3e194d..1a8c9d3725 100644 --- a/src/cmd/go/internal/modget/get.go +++ b/src/cmd/go/internal/modget/get.go @@ -380,10 +380,9 @@ func runGet(ctx context.Context, cmd *base.Command, args []string) { pkgs := load.PackagesAndErrors(ctx, pkgPatterns) load.CheckPackageErrors(pkgs) work.InstallPackages(ctx, pkgPatterns, pkgs) - // TODO(#40276): After Go 1.16, print a deprecation notice when building - // and installing main packages. 'go install pkg' or - // 'go install pkg@version' should be used instead. - // Give the specific argument to use if possible. + // TODO(#40276): After Go 1.16, print a deprecation notice when building and + // installing main packages. 'go install pkg' or 'go install pkg@version' + // should be used instead. Give the specific argument to use if possible. } if !modload.HasModRoot() { @@ -1453,7 +1452,18 @@ func (r *resolver) checkPackagesAndRetractions(ctx context.Context, pkgPatterns } } for _, pkg := range pkgs { - if _, _, err := modload.Lookup("", false, pkg); err != nil { + if dir, _, err := modload.Lookup("", false, pkg); err != nil { + if dir != "" && errors.Is(err, imports.ErrNoGo) { + // Since dir is non-empty, we must have located source files + // associated with either the package or its test — ErrNoGo must + // indicate that none of those source files happen to apply in this + // configuration. If we are actually building the package (no -d + // flag), the compiler will report the problem; otherwise, assume that + // the user is going to build or test it in some other configuration + // and suppress the error. + continue + } + base.SetExitStatus(1) if ambiguousErr := (*modload.AmbiguousImportError)(nil); errors.As(err, &ambiguousErr) { for _, m := range ambiguousErr.Modules { diff --git a/src/cmd/go/testdata/script/mod_get_pkgtags.txt b/src/cmd/go/testdata/script/mod_get_pkgtags.txt new file mode 100644 index 0000000000..c0a57f3fab --- /dev/null +++ b/src/cmd/go/testdata/script/mod_get_pkgtags.txt @@ -0,0 +1,116 @@ +# https://golang.org/issue/44106 +# 'go get' should fetch the transitive dependencies of packages regardless of +# tags, but shouldn't error out if the package is missing tag-guarded +# dependencies. + +# Control case: just adding the top-level module to the go.mod file does not +# fetch its dependencies. + +go mod edit -require example.net/tools@v0.1.0 +! go list -deps example.net/cmd/tool +stderr '^module example\.net/cmd provides package example\.net/cmd/tool and is replaced but not required; to add it:\n\tgo get example\.net/cmd@v0\.1\.0$' +go mod edit -droprequire example.net/tools + + +# 'go get -d' makes a best effort to fetch those dependencies, but shouldn't +# error out if dependencies of tag-guarded files are missing. + +go get -d example.net/tools@v0.1.0 + +! go list example.net/tools +stderr '^package example.net/tools: build constraints exclude all Go files in .*[/\\]tools$' + +go list -tags=tools -e -deps example.net/tools +stdout '^example.net/cmd/tool$' +stdout '^example.net/missing$' + +go list -deps example.net/cmd/tool + +! go list example.net/missing +stderr '^no required module provides package example.net/missing; to add it:\n\tgo get example.net/missing$' + + +# https://golang.org/issue/29268 +# 'go get' should fetch modules whose roots contain test-only packages, but +# without the -t flag shouldn't error out if the test has missing dependencies. + +go get -d example.net/testonly@v0.1.0 + +# With the -t flag, the test dependencies must resolve successfully. +! go get -d -t example.net/testonly@v0.1.0 +stderr '^example.net/testonly tested by\n\texample.net/testonly\.test imports\n\texample.net/missing: cannot find module providing package example.net/missing$' + + +# 'go get -d' should succeed for a module path that does not contain a package, +# but fail for a non-package subdirectory of a module. + +! go get -d example.net/missing/subdir@v0.1.0 +stderr '^go get: module example.net/missing@v0.1.0 found \(replaced by ./missing\), but does not contain package example.net/missing/subdir$' + +go get -d example.net/missing@v0.1.0 + + +# Getting the subdirectory should continue to fail even if the corresponding +# module is already present in the build list. + +! go get -d example.net/missing/subdir@v0.1.0 +stderr '^go get: module example.net/missing@v0.1.0 found \(replaced by ./missing\), but does not contain package example.net/missing/subdir$' + + +-- go.mod -- +module example.net/m + +go 1.15 + +replace ( + example.net/tools v0.1.0 => ./tools + example.net/cmd v0.1.0 => ./cmd + example.net/testonly v0.1.0 => ./testonly + example.net/missing v0.1.0 => ./missing +) + +-- tools/go.mod -- +module example.net/tools + +go 1.15 + +// Requirements intentionally omitted. + +-- tools/tools.go -- +// +build tools + +package tools + +import ( + _ "example.net/cmd/tool" + _ "example.net/missing" +) + +-- cmd/go.mod -- +module example.net/cmd + +go 1.16 +-- cmd/tool/tool.go -- +package main + +func main() {} + +-- testonly/go.mod -- +module example.net/testonly + +go 1.15 +-- testonly/testonly_test.go -- +package testonly_test + +import _ "example.net/missing" + +func Test(t *testing.T) {} + +-- missing/go.mod -- +module example.net/missing + +go 1.15 +-- missing/README.txt -- +There are no Go source files here. +-- missing/subdir/README.txt -- +There are no Go source files here either. -- cgit v1.2.3-54-g00ecf From ed8079096fe2e78d6dcb8002758774dca6d24eee Mon Sep 17 00:00:00 2001 From: Cherry Zhang Date: Wed, 10 Feb 2021 12:43:18 -0500 Subject: cmd/compile: mark concrete call of reflect.(*rtype).Method as REFLECTMETHOD For functions that call reflect.Type.Method (or MethodByName), we mark it as REFLECTMETHOD, which tells the linker that methods can be retrieved via reflection and the linker keeps all exported methods live. Currently, this marking expects exactly the interface call reflect.Type.Method (or MethodByName). But now the compiler can devirtualize that call to a concrete call reflect.(*rtype).Method (or MethodByName), which is not handled and causing the linker to discard methods too aggressively. Handle the latter in this CL. Fixes #44207. Change-Id: Ia4060472dbff6ab6a83d2ca8e60a3e3f180ee832 Reviewed-on: https://go-review.googlesource.com/c/go/+/290950 Trust: Cherry Zhang Reviewed-by: Matthew Dempsky --- src/cmd/compile/internal/gc/walk.go | 16 +++++++++++++++- test/reflectmethod7.go | 24 ++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 test/reflectmethod7.go diff --git a/src/cmd/compile/internal/gc/walk.go b/src/cmd/compile/internal/gc/walk.go index 2133a160b2..98ebb23991 100644 --- a/src/cmd/compile/internal/gc/walk.go +++ b/src/cmd/compile/internal/gc/walk.go @@ -550,8 +550,12 @@ opswitch: case OCLOSUREVAR, OCFUNC: case OCALLINTER, OCALLFUNC, OCALLMETH: - if n.Op == OCALLINTER { + if n.Op == OCALLINTER || n.Op == OCALLMETH { + // We expect both interface call reflect.Type.Method and concrete + // call reflect.(*rtype).Method. usemethod(n) + } + if n.Op == OCALLINTER { markUsedIfaceMethod(n) } @@ -3710,6 +3714,16 @@ func usemethod(n *Node) { } } + // Don't mark reflect.(*rtype).Method, etc. themselves in the reflect package. + // Those functions may be alive via the itab, which should not cause all methods + // alive. We only want to mark their callers. + if myimportpath == "reflect" { + switch Curfn.Func.Nname.Sym.Name { // TODO: is there a better way than hardcoding the names? + case "(*rtype).Method", "(*rtype).MethodByName", "(*interfaceType).Method", "(*interfaceType).MethodByName": + return + } + } + // Note: Don't rely on res0.Type.String() since its formatting depends on multiple factors // (including global variables such as numImports - was issue #19028). // Also need to check for reflect package itself (see Issue #38515). diff --git a/test/reflectmethod7.go b/test/reflectmethod7.go new file mode 100644 index 0000000000..42429978b4 --- /dev/null +++ b/test/reflectmethod7.go @@ -0,0 +1,24 @@ +// run + +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// See issue 44207. + +package main + +import "reflect" + +type S int + +func (s S) M() {} + +func main() { + t := reflect.TypeOf(S(0)) + fn, ok := reflect.PtrTo(t).MethodByName("M") + if !ok { + panic("FAIL") + } + fn.Func.Call([]reflect.Value{reflect.New(t)}) +} -- cgit v1.2.3-54-g00ecf From e5b08e6d5cecb646066c0cadddf6300e2a10ffb2 Mon Sep 17 00:00:00 2001 From: Russ Cox Date: Tue, 9 Feb 2021 13:46:53 -0500 Subject: io/fs: allow backslash in ValidPath, reject in os.DirFS.Open Rejecting backslash introduces problems with presenting underlying OS file systems that contain names with backslash. Rejecting backslash also does not Windows-proof the syntax, because colon can also be a path separator. And we are not going to reject colon from all names. So don't reject backslash either. There is a similar problem on Windows with names containing slashes, but those are more difficult (though not impossible) to create. Also document and enforce that paths must be UTF-8. Fixes #44166. Change-Id: Iac7a9a268025c1fd31010dbaf3f51e1660c7ae2a Reviewed-on: https://go-review.googlesource.com/c/go/+/290709 TryBot-Result: Go Bot Reviewed-by: Bryan C. Mills Trust: Russ Cox Run-TryBot: Russ Cox --- src/io/fs/fs.go | 23 ++++++++++++++--------- src/io/fs/fs_test.go | 7 ++++--- src/os/file.go | 13 ++++++++++++- src/os/os_test.go | 34 ++++++++++++++++++++++++++++++++++ 4 files changed, 64 insertions(+), 13 deletions(-) diff --git a/src/io/fs/fs.go b/src/io/fs/fs.go index c330f123ad..3d2e2ee2ac 100644 --- a/src/io/fs/fs.go +++ b/src/io/fs/fs.go @@ -10,6 +10,7 @@ package fs import ( "internal/oserror" "time" + "unicode/utf8" ) // An FS provides access to a hierarchical file system. @@ -32,15 +33,22 @@ type FS interface { // ValidPath reports whether the given path name // is valid for use in a call to Open. -// Path names passed to open are unrooted, slash-separated -// sequences of path elements, like “x/y/z”. -// Path names must not contain a “.” or “..” or empty element, +// +// Path names passed to open are UTF-8-encoded, +// unrooted, slash-separated sequences of path elements, like “x/y/z”. +// Path names must not contain an element that is “.” or “..” or the empty string, // except for the special case that the root directory is named “.”. -// Leading and trailing slashes (like “/x” or “x/”) are not allowed. +// Paths must not start or end with a slash: “/x” and “x/” are invalid. // -// Paths are slash-separated on all systems, even Windows. -// Backslashes must not appear in path names. +// Note that paths are slash-separated on all systems, even Windows. +// Paths containing other characters such as backslash and colon +// are accepted as valid, but those characters must never be +// interpreted by an FS implementation as path element separators. func ValidPath(name string) bool { + if !utf8.ValidString(name) { + return false + } + if name == "." { // special case return true @@ -50,9 +58,6 @@ func ValidPath(name string) bool { for { i := 0 for i < len(name) && name[i] != '/' { - if name[i] == '\\' { - return false - } i++ } elem := name[:i] diff --git a/src/io/fs/fs_test.go b/src/io/fs/fs_test.go index 8d395fc0db..aae1a7606f 100644 --- a/src/io/fs/fs_test.go +++ b/src/io/fs/fs_test.go @@ -33,9 +33,10 @@ var isValidPathTests = []struct { {"x/..", false}, {"x/../y", false}, {"x//y", false}, - {`x\`, false}, - {`x\y`, false}, - {`\x`, false}, + {`x\`, true}, + {`x\y`, true}, + {`x:y`, true}, + {`\x`, true}, } func TestValidPath(t *testing.T) { diff --git a/src/os/file.go b/src/os/file.go index 416bc0efa6..52dd94339b 100644 --- a/src/os/file.go +++ b/src/os/file.go @@ -620,10 +620,21 @@ func DirFS(dir string) fs.FS { return dirFS(dir) } +func containsAny(s, chars string) bool { + for i := 0; i < len(s); i++ { + for j := 0; j < len(chars); j++ { + if s[i] == chars[j] { + return true + } + } + } + return false +} + type dirFS string func (dir dirFS) Open(name string) (fs.File, error) { - if !fs.ValidPath(name) { + if !fs.ValidPath(name) || runtime.GOOS == "windows" && containsAny(name, `\:`) { return nil, &PathError{Op: "open", Path: name, Err: ErrInvalid} } f, err := Open(string(dir) + "/" + name) diff --git a/src/os/os_test.go b/src/os/os_test.go index ee54b4aba1..a32e5fc11e 100644 --- a/src/os/os_test.go +++ b/src/os/os_test.go @@ -2719,6 +2719,40 @@ func TestDirFS(t *testing.T) { if err := fstest.TestFS(DirFS("./testdata/dirfs"), "a", "b", "dir/x"); err != nil { t.Fatal(err) } + + // Test that Open does not accept backslash as separator. + d := DirFS(".") + _, err := d.Open(`testdata\dirfs`) + if err == nil { + t.Fatalf(`Open testdata\dirfs succeeded`) + } +} + +func TestDirFSPathsValid(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skipf("skipping on Windows") + } + + d := t.TempDir() + if err := os.WriteFile(filepath.Join(d, "control.txt"), []byte(string("Hello, world!")), 0644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(d, `e:xperi\ment.txt`), []byte(string("Hello, colon and backslash!")), 0644); err != nil { + t.Fatal(err) + } + + fsys := os.DirFS(d) + err := fs.WalkDir(fsys, ".", func(path string, e fs.DirEntry, err error) error { + if fs.ValidPath(e.Name()) { + t.Logf("%q ok", e.Name()) + } else { + t.Errorf("%q INVALID", e.Name()) + } + return nil + }) + if err != nil { + t.Fatal(err) + } } func TestReadFileProc(t *testing.T) { -- cgit v1.2.3-54-g00ecf From 930c2c9a6810b54d84dc499120219a6cb4563fd7 Mon Sep 17 00:00:00 2001 From: Russ Cox Date: Tue, 9 Feb 2021 17:34:09 -0500 Subject: cmd/go: reject embedded files that can't be packed into modules If the file won't be packed into a module, don't put those files into embeds. Otherwise people will be surprised when things work locally but not when imported by another module. Observed on CL 290709 Change-Id: Ia0ef7d0e0f5e42473c2b774e57c843e68a365bc7 Reviewed-on: https://go-review.googlesource.com/c/go/+/290809 Trust: Russ Cox Run-TryBot: Russ Cox TryBot-Result: Go Bot Reviewed-by: Bryan C. Mills Reviewed-by: Jay Conrod --- src/cmd/go/internal/load/pkg.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/cmd/go/internal/load/pkg.go b/src/cmd/go/internal/load/pkg.go index 3a274a3ad1..8b12faf4cd 100644 --- a/src/cmd/go/internal/load/pkg.go +++ b/src/cmd/go/internal/load/pkg.go @@ -36,6 +36,8 @@ import ( "cmd/go/internal/str" "cmd/go/internal/trace" "cmd/internal/sys" + + "golang.org/x/mod/module" ) var IgnoreImports bool // control whether we ignore imports in packages @@ -2090,6 +2092,9 @@ func validEmbedPattern(pattern string) bool { // can't or won't be included in modules and therefore shouldn't be treated // as existing for embedding. func isBadEmbedName(name string) bool { + if err := module.CheckFilePath(name); err != nil { + return true + } switch name { // Empty string should be impossible but make it bad. case "": -- cgit v1.2.3-54-g00ecf From 26ceae85a89dc4ea910cc0bfa209c85213a93725 Mon Sep 17 00:00:00 2001 From: DQNEO Date: Wed, 10 Feb 2021 14:46:54 +0900 Subject: spec: More precise wording in section on function calls. A caller is not always in a function. For example, a call can appear in top level declarations. e.g. var x = f() Change-Id: I29c4c3b7663249434fb2b8a6d0003267c77268cf Reviewed-on: https://go-review.googlesource.com/c/go/+/290849 Reviewed-by: Rob Pike Reviewed-by: Ian Lance Taylor Reviewed-by: Robert Griesemer Trust: Robert Griesemer --- doc/go_spec.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/go_spec.html b/doc/go_spec.html index c9e14a3fec..59c9ce3c43 100644 --- a/doc/go_spec.html +++ b/doc/go_spec.html @@ -1,6 +1,6 @@ @@ -3446,7 +3446,7 @@ In a function call, the function value and arguments are evaluated in After they are evaluated, the parameters of the call are passed by value to the function and the called function begins execution. The return parameters of the function are passed by value -back to the calling function when the function returns. +back to the caller when the function returns.

-- cgit v1.2.3-54-g00ecf From 864d4f1c6b364e13c0a4008bc203f336b0027f44 Mon Sep 17 00:00:00 2001 From: Jay Conrod Date: Thu, 11 Feb 2021 10:27:55 -0500 Subject: cmd/go: multiple small 'go help' fixes * Link to privacy policies for proxy.golang.org and sum.golang.org in 'go help modules'. It's important that both policies are linked from the go command's documentation. * Fix wording and typo in 'go help vcs' following comments in CL 290992, which adds reference documentation for GOVCS. * Fix whitespace on GOVCS in 'go help environment'. For #41730 Change-Id: I86abceacd4962b748361244026f219157c9285e9 Reviewed-on: https://go-review.googlesource.com/c/go/+/291230 Trust: Jay Conrod Run-TryBot: Jay Conrod Reviewed-by: Bryan C. Mills TryBot-Result: Go Bot --- src/cmd/go/alldocs.go | 30 ++++++++++++++++++++++-------- src/cmd/go/internal/help/helpdoc.go | 2 +- src/cmd/go/internal/modget/get.go | 17 ++++++++++------- src/cmd/go/internal/modload/help.go | 13 +++++++++++-- 4 files changed, 44 insertions(+), 18 deletions(-) diff --git a/src/cmd/go/alldocs.go b/src/cmd/go/alldocs.go index 49d390297c..e7c63f0749 100644 --- a/src/cmd/go/alldocs.go +++ b/src/cmd/go/alldocs.go @@ -1808,7 +1808,7 @@ // The directory where the go command will write // temporary source files, packages, and binaries. // GOVCS -// Lists version control commands that may be used with matching servers. +// Lists version control commands that may be used with matching servers. // See 'go help vcs'. // // Environment variables for use with cgo: @@ -2410,6 +2410,17 @@ // // For a detailed reference on modules, see https://golang.org/ref/mod. // +// By default, the go command may download modules from https://proxy.golang.org. +// It may authenticate modules using the checksum database at +// https://sum.golang.org. Both services are operated by the Go team at Google. +// The privacy policies for these services are available at +// https://proxy.golang.org/privacy and https://sum.golang.org/privacy, +// respectively. +// +// The go command's download behavior may be configured using GOPROXY, GOSUMDB, +// GOPRIVATE, and other environment variables. See 'go help environment' +// and https://golang.org/ref/mod#private-module-privacy for more information. +// // // Module authentication using go.sum // @@ -2868,20 +2879,23 @@ // legal reasons). Therefore, clients can still access public code served from // Bazaar, Fossil, or Subversion repositories by default, because those downloads // use the Go module mirror, which takes on the security risk of running the -// version control commands, using a custom sandbox. +// version control commands using a custom sandbox. // // The GOVCS variable can be used to change the allowed version control systems // for specific packages (identified by a module or import path). -// The GOVCS variable applies both when using modules and when using GOPATH. -// When using modules, the patterns match against the module path. -// When using GOPATH, the patterns match against the import path -// corresponding to the root of the version control repository. +// The GOVCS variable applies when building package in both module-aware mode +// and GOPATH mode. When using modules, the patterns match against the module path. +// When using GOPATH, the patterns match against the import path corresponding to +// the root of the version control repository. // // The general form of the GOVCS setting is a comma-separated list of // pattern:vcslist rules. The pattern is a glob pattern that must match // one or more leading elements of the module or import path. The vcslist // is a pipe-separated list of allowed version control commands, or "all" -// to allow use of any known command, or "off" to allow nothing. +// to allow use of any known command, or "off" to disallow all commands. +// Note that if a module matches a pattern with vcslist "off", it may still be +// downloaded if the origin server uses the "mod" scheme, which instructs the +// go command to download the module using the GOPROXY protocol. // The earliest matching pattern in the list applies, even if later patterns // might also match. // @@ -2889,7 +2903,7 @@ // // GOVCS=github.com:git,evil.com:off,*:git|hg // -// With this setting, code with an module or import path beginning with +// With this setting, code with a module or import path beginning with // github.com/ can only use git; paths on evil.com cannot use any version // control command, and all other paths (* matches everything) can use // only git or hg. diff --git a/src/cmd/go/internal/help/helpdoc.go b/src/cmd/go/internal/help/helpdoc.go index e07ad0e1db..57cee4ff96 100644 --- a/src/cmd/go/internal/help/helpdoc.go +++ b/src/cmd/go/internal/help/helpdoc.go @@ -542,7 +542,7 @@ General-purpose environment variables: The directory where the go command will write temporary source files, packages, and binaries. GOVCS - Lists version control commands that may be used with matching servers. + Lists version control commands that may be used with matching servers. See 'go help vcs'. Environment variables for use with cgo: diff --git a/src/cmd/go/internal/modget/get.go b/src/cmd/go/internal/modget/get.go index 1a8c9d3725..dccacd3d1e 100644 --- a/src/cmd/go/internal/modget/get.go +++ b/src/cmd/go/internal/modget/get.go @@ -176,20 +176,23 @@ packages or when the mirror refuses to serve a public package (typically for legal reasons). Therefore, clients can still access public code served from Bazaar, Fossil, or Subversion repositories by default, because those downloads use the Go module mirror, which takes on the security risk of running the -version control commands, using a custom sandbox. +version control commands using a custom sandbox. The GOVCS variable can be used to change the allowed version control systems for specific packages (identified by a module or import path). -The GOVCS variable applies both when using modules and when using GOPATH. -When using modules, the patterns match against the module path. -When using GOPATH, the patterns match against the import path -corresponding to the root of the version control repository. +The GOVCS variable applies when building package in both module-aware mode +and GOPATH mode. When using modules, the patterns match against the module path. +When using GOPATH, the patterns match against the import path corresponding to +the root of the version control repository. The general form of the GOVCS setting is a comma-separated list of pattern:vcslist rules. The pattern is a glob pattern that must match one or more leading elements of the module or import path. The vcslist is a pipe-separated list of allowed version control commands, or "all" -to allow use of any known command, or "off" to allow nothing. +to allow use of any known command, or "off" to disallow all commands. +Note that if a module matches a pattern with vcslist "off", it may still be +downloaded if the origin server uses the "mod" scheme, which instructs the +go command to download the module using the GOPROXY protocol. The earliest matching pattern in the list applies, even if later patterns might also match. @@ -197,7 +200,7 @@ For example, consider: GOVCS=github.com:git,evil.com:off,*:git|hg -With this setting, code with an module or import path beginning with +With this setting, code with a module or import path beginning with github.com/ can only use git; paths on evil.com cannot use any version control command, and all other paths (* matches everything) can use only git or hg. diff --git a/src/cmd/go/internal/modload/help.go b/src/cmd/go/internal/modload/help.go index 1cb58961be..fd39ddd94e 100644 --- a/src/cmd/go/internal/modload/help.go +++ b/src/cmd/go/internal/modload/help.go @@ -6,8 +6,6 @@ package modload import "cmd/go/internal/base" -// TODO(rsc): The "module code layout" section needs to be written. - var HelpModules = &base.Command{ UsageLine: "modules", Short: "modules, module versions, and more", @@ -22,6 +20,17 @@ For a series of tutorials on modules, see https://golang.org/doc/tutorial/create-module. For a detailed reference on modules, see https://golang.org/ref/mod. + +By default, the go command may download modules from https://proxy.golang.org. +It may authenticate modules using the checksum database at +https://sum.golang.org. Both services are operated by the Go team at Google. +The privacy policies for these services are available at +https://proxy.golang.org/privacy and https://sum.golang.org/privacy, +respectively. + +The go command's download behavior may be configured using GOPROXY, GOSUMDB, +GOPRIVATE, and other environment variables. See 'go help environment' +and https://golang.org/ref/mod#private-module-privacy for more information. `, } -- cgit v1.2.3-54-g00ecf From 249da7ec020e194208c02c8eb6a04d017bf29fea Mon Sep 17 00:00:00 2001 From: Carlos Amedee Date: Wed, 10 Feb 2021 20:29:50 -0500 Subject: CONTRIBUTORS: update for the Go 1.16 release This update was created using the updatecontrib command: go get golang.org/x/build/cmd/updatecontrib cd gotip updatecontrib With manual changes based on publicly available information to canonicalize letter case and formatting for a few names. For #12042. Change-Id: I030b77e8ebcc7fe02106f0f264acdfb0b56e20d9 Reviewed-on: https://go-review.googlesource.com/c/go/+/291189 Trust: Carlos Amedee Run-TryBot: Carlos Amedee TryBot-Result: Go Bot Reviewed-by: Ian Lance Taylor Reviewed-by: Alexander Rakoczy Reviewed-by: Dmitri Shuralyov --- CONTRIBUTORS | 158 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 158 insertions(+) diff --git a/CONTRIBUTORS b/CONTRIBUTORS index cebc92f53f..ccbe4627f3 100644 --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -30,6 +30,7 @@ Aaron Bieber Aaron Cannon Aaron France Aaron Jacobs +Aaron Jensen Aaron Kemp Aaron Patterson Aaron Stein @@ -71,9 +72,11 @@ Ahmet Alp Balkan Ahmet Soormally Ahmy Yulrizka Ahsun Ahmed +Aidan Coyle Aiden Scandella Ainar Garipov Aishraj Dahal +Ajanthan Balachandran Akhil Indurti Akihiro Suda Akshat Kumar @@ -104,9 +107,11 @@ Alex Buchanan Alex Carol Alex Gaynor Alex Harford +Alex Hays Alex Jin Alex Kohler Alex Myasoedov +Alex Opie Alex Plugaru Alex Schroeder Alex Sergeyev @@ -119,6 +124,7 @@ Alexander F Rødseth Alexander Greim Alexander Guz Alexander Kauer +Alexander Klauer Alexander Kucherenko Alexander Larsson Alexander Lourier @@ -150,16 +156,19 @@ Alexey Naidonov Alexey Neganov Alexey Palazhchenko Alexey Semenyuk +Alexey Vilenskiy Alexis Hildebrandt Alexis Hunt Alexis Imperial-Legrand Ali Farooq Ali Rizvi-Santiago Aliaksandr Valialkin +Alice Merrick Alif Rachmawadi Allan Simon Allen Li Alok Menghrajani +Alwin Doss Aman Gupta Amarjeet Anand Amir Mohammad Saied @@ -168,6 +177,8 @@ Amrut Joshi An Long An Xiao Anand K. Mistry +Ananya Saxena +Anatol Pomozov Anders Pearson Anderson Queiroz André Carvalho @@ -199,6 +210,7 @@ Andrew G. Morgan Andrew Gerrand Andrew Harding Andrew Jackura +Andrew Kemm Andrew Louis Andrew Lutomirski Andrew Medvedev @@ -216,6 +228,7 @@ Andrew Werner Andrew Wilkins Andrew Williams Andrew Z Allen +Andrey Bokhanko Andrey Mirtchovski Andrey Petrov Andrii Soldatenko @@ -230,6 +243,7 @@ Andy Maloney Andy Pan Andy Walker Andy Wang +Andy Williams Andzej Maciusovic Anfernee Yongkun Gui Angelo Bulfone @@ -274,6 +288,7 @@ Arne Hormann Arnout Engelen Aron Nopanen Artem Alekseev +Artem Khvastunov Artem Kolin Arthur Fabre Arthur Khashaev @@ -281,8 +296,10 @@ Artyom Pervukhin Arvindh Rajesh Tamilmani Ashish Gandhi Asim Shankar +Assel Meher Atin Malaviya Ato Araki +Atsushi Toyama Audrey Lim Audrius Butkevicius Augusto Roman @@ -291,6 +308,7 @@ Aurélien Rainone Aurélio A. Heckert Austin Clements Avi Flax +Aviv Klasquin Komissar awaw fumin Awn Umar Axel Wagner @@ -298,6 +316,7 @@ Ayan George Ayanamist Yang Ayke van Laethem Aymerick Jéhanne +Ayzat Sadykov Azat Kaumov Baiju Muthukadan Balaram Makam @@ -308,10 +327,12 @@ Bartosz Grzybowski Bartosz Oler Bastian Ike Ben Burkert +Ben Cartwright-Cox Ben Eitzen Ben Fried Ben Haines Ben Hoyt +Ben Kraft Ben Laurie Ben Lubar Ben Lynn @@ -319,6 +340,7 @@ Ben Olive Ben Schwartz Ben Shi Ben Toews +Benjamin Barenblat Benjamin Black Benjamin Cable Benjamin Hsieh @@ -356,6 +378,7 @@ Bobby Powers Boqin Qin Boris Nagaev Borja Clemente +Boshi Lian Brad Burch Brad Erickson Brad Fitzpatrick @@ -368,10 +391,12 @@ Bradford Lamson-Scribner Bradley Falzon Brady Catherman Brady Sullivan +Branden J. Brown Brandon Bennett Brandon Gilmore Brandon Philips Brandon Ryan +Brave Cow Brayden Cloud Brendan Daniel Tracey Brendan O'Dea @@ -389,6 +414,7 @@ Brian Slesinsky Brian Smith Brian Starke Bryan Alexander +Bryan Boreham Bryan C. Mills Bryan Chan Bryan Ford @@ -407,6 +433,7 @@ Carl Mastrangelo Carl Shapiro Carlisia Campos Carlo Alberto Ferraris +Carlos Alexandro Becker Carlos Amedee Carlos Castillo Carlos Cirello @@ -422,6 +449,7 @@ Casey Callendrello Casey Marshall Catalin Nicutar Catalin Patulea +Cathal O'Callaghan Cedric Staub Cezar Sá Espinola Chad Rosier @@ -434,10 +462,14 @@ Charles Kenney Charles L. Dorian Charles Lee Charles Weill +Charlotte Brandhorst-Satzkorn Chauncy Cullitan +Chen Zhidong Chen Zhihan Cherry Zhang Chew Choon Keat +Chiawen Chen +Chirag Sukhala Cholerae Hu Chotepud Teo Chris Ball @@ -460,6 +492,8 @@ Chris Raynor Chris Roche Chris Smith Chris Stockton +Chris Taylor +Chris Waldon Chris Zou Christian Alexander Christian Couder @@ -467,6 +501,7 @@ Christian Himpel Christian Muehlhaeuser Christian Pellegrin Christian R. Petrin +Christian Svensson Christine Hansmann Christoffer Buchholz Christoph Blecker @@ -474,6 +509,7 @@ Christoph Hack Christopher Cahoon Christopher Guiney Christopher Henderson +Christopher Hlubek Christopher Koch Christopher Loessl Christopher Nelson @@ -506,7 +542,10 @@ Costin Chirvasuta Craig Citro Cristian Staretu Cuihtlauac ALVARADO +Cuong Manh Le +Curtis La Graff Cyrill Schumacher +Dai Jie Daisuke Fujita Daisuke Suzuki Daker Fernandes Pinheiro @@ -525,12 +564,14 @@ Dan Peterson Dan Pupius Dan Scales Dan Sinclair +Daniel Cohen Daniel Cormier Daniël de Kok Daniel Fleischman Daniel Ingram Daniel Johansson Daniel Kerwin +Daniel Kessler Daniel Krech Daniel Kumor Daniel Langner @@ -538,10 +579,12 @@ Daniel Lidén Daniel Lublin Daniel Mangum Daniel Martí +Daniel McCarney Daniel Morsing Daniel Nadasi Daniel Nephin Daniel Ortiz Pereira da Silva +Daniel S. Fava Daniel Skinner Daniel Speichert Daniel Theophanes @@ -563,6 +606,7 @@ Dave Cheney Dave Day Dave Grijalva Dave MacFarlane +Dave Pifke Dave Russell David Anderson David Barnett @@ -593,6 +637,7 @@ David McLeish David Ndungu David NewHamlet David Presotto +David Qu David R. Jenni David Sansome David Stainton @@ -642,6 +687,7 @@ Diwaker Gupta Dmitri Goutnik Dmitri Popov Dmitri Shuralyov +Dmitrii Okunev Dmitriy Cherchenko Dmitriy Dudkin Dmitriy Shelenin @@ -655,6 +701,7 @@ Dmitry Yakunin Doga Fincan Domas Tamašauskas Domen Ipavec +Dominic Della Valle Dominic Green Dominik Honnef Dominik Vogt @@ -696,6 +743,7 @@ Elias Naur Elliot Morrison-Reed Ellison Leão Emerson Lin +Emil Bektimirov Emil Hessman Emil Mursalimov Emilien Kenler @@ -760,6 +808,7 @@ Fatih Arslan Fazal Majid Fazlul Shahriar Federico Bond +Federico Guerinoni Federico Simoncelli Fedor Indutny Fedor Korotkiy @@ -781,6 +830,7 @@ Florin Patan Folke Behrens Ford Hurley Francesc Campoy +Francesco Guardiani Francesco Renzi Francisco Claude Francisco Rojas @@ -811,8 +861,10 @@ Gabriel Russell Gareth Paul Jones Garret Kelly Garrick Evans +Garry McNulty Gary Burd Gary Elliott +Gaurav Singh Gaurish Sharma Gautham Thambidorai Gauthier Jolly @@ -827,6 +879,7 @@ Georg Reinke George Gkirtsou George Hartzell George Shammas +George Tsilias Gerasimos (Makis) Maropoulos Gerasimos Dimitriadis Gergely Brautigam @@ -862,6 +915,7 @@ GitHub User @frennkie (6499251) GitHub User @geedchin (11672310) GitHub User @GrigoriyMikhalkin (3637857) GitHub User @hengwu0 (41297446) <41297446+hengwu0@users.noreply.github.com> +GitHub User @hitzhangjie (3725760) GitHub User @itchyny (375258) GitHub User @jinmiaoluo (39730824) GitHub User @jopbrown (6345470) @@ -873,6 +927,7 @@ GitHub User @LotusFenn (13775899) GitHub User @ly303550688 (11519839) GitHub User @madiganz (18340029) GitHub User @maltalex (10195391) +GitHub User @markruler (38225900) GitHub User @Matts966 (28551465) GitHub User @micnncim (21333876) GitHub User @mkishere (224617) <224617+mkishere@users.noreply.github.com> @@ -886,6 +941,8 @@ GitHub User @ramenjuniti (32011829) GitHub User @saitarunreddy (21041941) GitHub User @shogo-ma (9860598) GitHub User @skanehira (7888591) +GitHub User @soolaugust (10558124) +GitHub User @surechen (7249331) GitHub User @tatsumack (4510569) GitHub User @tell-k (26263) GitHub User @tennashi (10219626) @@ -908,6 +965,7 @@ Gordon Tyler Graham King Graham Miller Grant Griffiths +Green Lightning Greg Poirier Greg Steuck Greg Thelen @@ -920,6 +978,7 @@ Guilherme Garnier Guilherme Goncalves Guilherme Rezende Guillaume J. Charmes +Guillaume Sottas Günther Noack Guobiao Mei Guoliang Wang @@ -936,6 +995,8 @@ HAMANO Tsukasa Han-Wen Nienhuys Hang Qian Hanjun Kim +Hanlin Shi +Haoran Luo Haosdent Huang Harald Nordgren Hari haran @@ -950,9 +1011,11 @@ Håvard Haugen He Liu Hector Chu Hector Martin Cantero +Hein Khant Zaw Henning Schmiedehausen Henrik Edwards Henrik Hodne +Henrique Vicente Henry Adi Sumarto Henry Bubert Henry Chang @@ -969,6 +1032,7 @@ Hironao OTSUBO Hiroshi Ioka Hitoshi Mitake Holden Huang +Songlin Jiang Hong Ruiqi Hongfei Tan Horacio Duran @@ -990,6 +1054,7 @@ Ian Haken Ian Kent Ian Lance Taylor Ian Leue +Ian Tay Ian Zapolsky Ibrahim AshShohail Icarus Sparry @@ -997,9 +1062,11 @@ Iccha Sethi Idora Shinatose Ignacio Hagopian Igor Bernstein +Igor Bolotnikov Igor Dolzhikov Igor Vashyst Igor Zhilianin +Ikko Ashimine Illya Yalovyy Ilya Sinelnikov Ilya Tocar @@ -1037,6 +1104,7 @@ Jacob Blain Christen Jacob H. Haven Jacob Hoffman-Andrews Jacob Walker +Jaden Teng Jae Kwon Jake B Jakob Borg @@ -1044,6 +1112,7 @@ Jakob Weisblat Jakub Čajka Jakub Kaczmarzyk Jakub Ryszard Czarnowicz +Jakub Warczarek Jamal Carvalho James Aguilar James Bardin @@ -1056,9 +1125,11 @@ James Eady James Fysh James Gray James Hartig +James Kasten James Lawrence James Meneghello James Myers +James Naftel James Neve James Nugent James P. Cooper @@ -1108,6 +1179,7 @@ Javier Kohen Javier Revillas Javier Segura Jay Conrod +Jay Lee Jay Taylor Jay Weisskopf Jean de Klerk @@ -1140,14 +1212,17 @@ Jeremy Jay Jeremy Schlatter Jeroen Bobbeldijk Jeroen Simonetti +Jérôme Doucet Jerrin Shaji George Jess Frazelle Jesse Szwedko Jesús Espino Jia Zhan Jiacai Liu +Jiahao Lu Jianing Yu Jianqiao Li +Jiayu Yi Jie Ma Jihyun Yu Jim Cote @@ -1183,6 +1258,7 @@ Joey Geiger Johan Brandhorst Johan Euphrosine Johan Jansson +Johan Knutzen Johan Sageryd John Asmuth John Beisley @@ -1210,6 +1286,7 @@ Johnny Luo Jon Chen Jon Johnson Jonas Bernoulli +Jonathan Albrecht Jonathan Allie Jonathan Amsterdam Jonathan Boulle @@ -1223,6 +1300,7 @@ Jonathan Pentecost Jonathan Pittman Jonathan Rudenberg Jonathan Stacks +Jonathan Swinney Jonathan Wills Jonathon Lacher Jongmin Kim @@ -1233,6 +1311,7 @@ Jordan Krage Jordan Lewis Jordan Liggitt Jordan Rhee +Jordan Rupprecht Jordi Martin Jorge Araya Jorge L. Fatta @@ -1276,6 +1355,7 @@ Julien Salleyron Julien Schmidt Julio Montes Jun Zhang +Junchen Li Junda Liu Jungho Ahn Junya Hayashi @@ -1287,6 +1367,7 @@ Justin Nuß Justyn Temme Kai Backman Kai Dong +Kai Lüke Kai Trukenmüller Kale Blankenship Kaleb Elwert @@ -1314,6 +1395,7 @@ Kazuhiro Sera KB Sriram Keegan Carruthers-Smith Kei Son +Keiichi Hirobe Keiji Yoshida Keisuke Kishimoto Keith Ball @@ -1322,6 +1404,7 @@ Keith Rarick Kelly Heller Kelsey Hightower Kelvin Foo Chuan Lyi +Kemal Elmizan Ken Friedenbach Ken Rockot Ken Sedgwick @@ -1331,6 +1414,7 @@ Kenji Kaneda Kenji Yano Kenneth Shaw Kenny Grant +Kensei Nakada Kenta Mori Kerollos Magdy Ketan Parmar @@ -1342,10 +1426,12 @@ Kevin Gillette Kevin Kirsche Kevin Klues Kevin Malachowski +Kevin Parsons Kevin Ruffin Kevin Vu Kevin Zita Keyan Pishdadian +Keyuan Li Kezhu Wang Khosrow Moossavi Kieran Colford @@ -1358,6 +1444,7 @@ Kirill Smelkov Kirill Tatchihin Kirk Han Kirklin McDonald +KJ Tsanaktsidis Klaus Post Kodie Goodwin Koichi Shiraishi @@ -1371,6 +1458,7 @@ Kris Kwiatkowski Kris Nova Kris Rousey Kristopher Watts +Krzysztof Dąbrowski Kshitij Saraogi Kun Li Kunpei Sakai @@ -1412,8 +1500,10 @@ Leonardo Comelli Leonel Quinteros Lev Shamardin Lewin Bormann +Lewis Waddicor Liam Haworth Lily Chung +Lingchao Xin Lion Yang Liz Rice Lloyd Dewolf @@ -1427,6 +1517,7 @@ Luan Santos Lubomir I. Ivanov Luca Bruno Luca Greco +Luca Spiller Lucas Bremgartner Lucas Clemente Lucien Stuker @@ -1450,6 +1541,8 @@ Maarten Bezemer Maciej Dębski Madhu Rajanna Magnus Hiie +Mahdi Hosseini Moghaddam +Maia Lee Maicon Costa Mak Kolybabi Maksym Trykur @@ -1470,6 +1563,7 @@ Marcel Edmund Franke Marcel van Lohuizen Marcelo Cantos Marcelo E. Magallon +Marco Gazerro Marco Hennings Marcus Weiner Marcus Willock @@ -1481,6 +1575,7 @@ Marius A. Eriksen Marius Nuennerich Mark Adams Mark Bucciarelli +Mark Dain Mark Glines Mark Harrison Mark Percival @@ -1533,6 +1628,7 @@ Máté Gulyás Matej Baćo Mateus Amin Mateusz Czapliński +Matheus Alcantara Mathias Beke Mathias Hall-Andersen Mathias Leppich @@ -1566,6 +1662,7 @@ Matthew Waters Matthieu Hauglustaine Matthieu Olivier Matthijs Kooijman +Max Drosdo.www Max Riveiro Max Schmitt Max Semenik @@ -1603,6 +1700,7 @@ Michael Hudson-Doyle Michael Kasch Michael Käufl Michael Kelly +Michaël Lévesque-Dion Michael Lewis Michael MacInnis Michael Marineau @@ -1624,6 +1722,7 @@ Michael Teichgräber Michael Traver Michael Vetter Michael Vogt +Michail Kargakis Michal Bohuslávek Michal Cierniak Michał Derkacz @@ -1633,6 +1732,7 @@ Michal Pristas Michal Rostecki Michalis Kargakis Michel Lespinasse +Michele Di Pede Mickael Kerjean Mickey Reiss Miek Gieben @@ -1670,6 +1770,7 @@ Miquel Sabaté Solà Mirko Hansen Miroslav Genov Misty De Meo +Mohamed Attahri Mohit Agarwal Mohit kumar Bajoria Mohit Verma @@ -1683,6 +1784,7 @@ Môshe van der Sterre Mostyn Bramley-Moore Mrunal Patel Muhammad Falak R Wani +Muhammad Hamza Farrukh Muhammed Uluyol Muir Manders Mukesh Sharma @@ -1692,6 +1794,7 @@ Naman Aggarwal Nan Deng Nao Yonashiro Naoki Kanatani +Natanael Copa Nate Wilkinson Nathan Cantelmo Nathan Caza @@ -1708,6 +1811,7 @@ Nathaniel Cook Naveen Kumar Sangi Neeilan Selvalingam Neelesh Chandola +Nehal J Wani Neil Lyons Neuman Vong Neven Sajko @@ -1760,6 +1864,7 @@ Noel Georgi Norberto Lopes Norman B. Lancaster Nuno Cruces +Obei Sideg Obeyda Djeffal Odin Ugedal Oleg Bulatov @@ -1769,12 +1874,17 @@ Oling Cat Oliver Hookins Oliver Powell Oliver Stenbom +Oliver Tan Oliver Tonnhofer Olivier Antoine Olivier Duperray Olivier Poitrey Olivier Saingre +Olivier Wulveryck Omar Jarjur +Onkar Jadhav +Ori Bernstein +Ori Rawlings Oryan Moshe Osamu TONOMORI Özgür Kesim @@ -1798,7 +1908,9 @@ Pat Moroney Patrick Barker Patrick Crosby Patrick Gavlin +Patrick Gundlach Patrick Higgins +Patrick Jones Patrick Lee Patrick Mézard Patrick Mylund Nielsen @@ -1811,6 +1923,9 @@ Paul Borman Paul Boyd Paul Chang Paul D. Weber +Paul Davis <43160081+Pawls@users.noreply.github.com> +Paul E. Murphy +Paul Forgey Paul Hammond Paul Hankin Paul Jolly @@ -1836,7 +1951,9 @@ Pavel Zinovkin Pavlo Sumkin Pawel Knap Pawel Szczur +Paweł Szulik Pei Xian Chee +Pei-Ming Wu Percy Wegmann Perry Abbott Petar Dambovaliev @@ -1876,6 +1993,7 @@ Philip Hofer Philip K. Warren Philip Nelson Philipp Stephani +Phillip Campbell <15082+phillc@users.noreply.github.com> Pierre Carru Pierre Durand Pierre Prinetti @@ -1885,6 +2003,7 @@ Pieter Droogendijk Pietro Gagliardi Piyush Mishra Plekhanov Maxim +Poh Zi How Polina Osadcha Pontus Leitzler Povilas Versockas @@ -1904,14 +2023,17 @@ Quentin Perez Quentin Renard Quentin Smith Quey-Liang Kao +Quim Muntal Quinn Slack Quinten Yearsley Quoc-Viet Nguyen +Radek Simko Radek Sohlich Radu Berinde Rafal Jeczalik Raghavendra Nagaraj Rahul Chaudhry +Rahul Wadhwani Raif S. Naffah Rajat Goel Rajath Agasthya @@ -1935,6 +2057,7 @@ Ren Ogaki Rens Rikkerink Rhys Hiltner Ricardo Padilha +Ricardo Pchevuzinske Katz Ricardo Seriani Richard Barnes Richard Crowley @@ -1991,6 +2114,7 @@ Roman Kollár Roman Shchekin Ron Hashimoto Ron Minnich +Ronnie Ebrin Ross Chater Ross Kinsey Ross Light @@ -2010,6 +2134,7 @@ Ryan Brown Ryan Canty Ryan Dahl Ryan Hitchman +Ryan Kohler Ryan Lower Ryan Roden-Corrent Ryan Seys @@ -2023,7 +2148,9 @@ S.Çağlar Onur Sabin Mihai Rapan Sad Pencil Sai Cheemalapati +Sai Kiran Dasika Sakeven Jiang +Salaheddin M. Mahmud Salmān Aljammāz Sam Arnold Sam Boyer @@ -2033,6 +2160,7 @@ Sam Ding Sam Hug Sam Thorogood Sam Whited +Sam Xie Sameer Ajmani Sami Commerot Sami Pönkänen @@ -2042,6 +2170,7 @@ Samuele Pedroni Sander van Harmelen Sanjay Menakuru Santhosh Kumar Tekuri +Santiago De la Cruz <51337247+xhit@users.noreply.github.com> Sarah Adams Sardorbek Pulatov Sascha Brawer @@ -2062,6 +2191,7 @@ Sean Chittenden Sean Christopherson Sean Dolphin Sean Harger +Sean Hildebrand Sean Liao Sean Rees Sebastiaan van Stijn @@ -2094,10 +2224,12 @@ Serhii Aheienko Seth Hoenig Seth Vargo Shahar Kohanim +Shailesh Suryawanshi Shamil Garatuev Shane Hansen Shang Jian Ding Shaozhen Ding +Shaquille Que Shaquille Wyan Que Shaun Dunning Shawn Elliott @@ -2108,8 +2240,11 @@ Shenghou Ma Shengjing Zhu Shengyu Zhang Shi Han Ng +ShihCheng Tu Shijie Hao +Shin Fan Shinji Tanaka +Shinnosuke Sawada <6warashi9@gmail.com> Shintaro Kaneko Shivakumar GN Shivani Singhal @@ -2121,17 +2256,21 @@ Silvan Jegen Simarpreet Singh Simon Drake Simon Ferquel +Simon Frei Simon Jefford Simon Rawet Simon Rozman +Simon Ser Simon Thulbourn Simon Whitehead Sina Siadat Sjoerd Siebinga Sokolov Yura Song Gao +Songjiayang Soojin Nam Søren L. Hansen +Sparrow Li Spencer Kocot Spencer Nelson Spencer Tung @@ -2140,12 +2279,14 @@ Srdjan Petrovic Sridhar Venkatakrishnan Srinidhi Kaushik StalkR +Stan Hu Stan Schwertly Stanislav Afanasev Steeve Morin Stefan Baebler Stefan Nilsson Stepan Shabalin +Stephan Klatt Stephan Renatus Stephan Zuercher Stéphane Travostino @@ -2163,13 +2304,16 @@ Steve Mynott Steve Newman Steve Phillips Steve Streeting +Steve Traut Steven Buss Steven Elliot Harris Steven Erenst Steven Hartland Steven Littiebrant +Steven Maude Steven Wilkin Stuart Jansen +Subham Sarkar Sue Spence Sugu Sougoumarane Suharsh Sivakumar @@ -2193,6 +2337,7 @@ Taesu Pyo Tai Le Taj Khattra Takashi Matsuo +Takashi Mima Takayoshi Nishida Takeshi YAMANASHI <9.nashi@gmail.com> Takuto Ikuta @@ -2221,6 +2366,7 @@ Thanatat Tamtan The Hatsune Daishi Thiago Avelino Thiago Fransosi Farina +Thom Wiggers Thomas Alan Copeland Thomas Bonfort Thomas Bouldin @@ -2245,6 +2391,7 @@ Tim Ebringer Tim Heckman Tim Henderson Tim Hockin +Tim King Tim Möhlmann Tim Swast Tim Wright @@ -2252,8 +2399,10 @@ Tim Xu Timmy Douglas Timo Savola Timo Truyts +Timothy Gu Timothy Studd Tipp Moseley +Tiwei Bie Tobias Assarsson Tobias Columbus Tobias Klauser @@ -2268,11 +2417,13 @@ Tom Lanyon Tom Levy Tom Limoncelli Tom Linford +Tom Panton Tom Parkin Tom Payne Tom Szymanski Tom Thorogood Tom Wilkie +Tom Zierbock Tomas Dabasinskas Tommy Schaefer Tomohiro Kusumoto @@ -2298,6 +2449,7 @@ Tristan Colgate Tristan Ooohry Tristan Rice Troels Thomsen +Trong Bui Trung Nguyen Tsuji Daishiro Tudor Golubenco @@ -2308,6 +2460,7 @@ Tyler Bunnell Tyler Treat Tyson Andre Tzach Shabtay +Tzu-Chiao Yeh Tzu-Jung Lee Udalov Max Ugorji Nwoke @@ -2316,6 +2469,7 @@ Ulrich Kunitz Umang Parmar Uriel Mangado Urvil Patel +Utkarsh Dixit <53217283+utkarsh-extc@users.noreply.github.com> Uttam C Pawar Vadim Grek Vadim Vygonets @@ -2327,6 +2481,7 @@ Venil Noronha Veselkov Konstantin Viacheslav Poturaev Victor Chudnovsky +Victor Michel Victor Vrantchan Vignesh Ramachandra Vikas Kedia @@ -2341,6 +2496,7 @@ Visweswara R Vitaly Zdanevich Vitor De Mario Vivek Sekhar +Vivek V Vivian Liang Vlad Krasnov Vladimir Evgrafov @@ -2392,6 +2548,7 @@ Wu Yunzhou Xi Ruoyao Xia Bin Xiangdong Ji +Xiaodong Liu Xing Xing Xingqang Bai Xu Fei @@ -2459,6 +2616,7 @@ Zhou Peng Ziad Hatahet Ziheng Liu Zorion Arrizabalaga +Zyad A. Ali Максадбек Ахмедов Максим Федосеев Роман Хавроненко -- cgit v1.2.3-54-g00ecf From ff0e93ea313e53f08018b90bada2edee267a8f55 Mon Sep 17 00:00:00 2001 From: "Bryan C. Mills" Date: Thu, 11 Feb 2021 16:24:26 -0500 Subject: doc/go1.16: note that package path elements beginning with '.' are disallowed For #43985 Change-Id: I1a16f66800c5c648703f0a0d2ad75024525a710f Reviewed-on: https://go-review.googlesource.com/c/go/+/291389 Trust: Bryan C. Mills Run-TryBot: Bryan C. Mills TryBot-Result: Go Bot Reviewed-by: Jay Conrod --- doc/go1.16.html | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/doc/go1.16.html b/doc/go1.16.html index f6f72c3882..d5de0ee5ce 100644 --- a/doc/go1.16.html +++ b/doc/go1.16.html @@ -174,10 +174,12 @@ Do not send CLs removing the interior tags from such phrases. non-reproducible builds.

-

- The go command now disallows non-ASCII import paths in module - mode. Non-ASCII module paths have already been disallowed so this change - affects module subdirectory paths that contain non-ASCII characters. +

+ In module mode, the go command now disallows import paths that + include non-ASCII characters or path elements with a leading dot character + (.). Module paths with these characters were already disallowed + (see Module paths and versions), + so this change affects only paths within module subdirectories.

Embedding Files

-- cgit v1.2.3-54-g00ecf From 66c27093d0df8be8a75b1ae35fe4ab2003fe028e Mon Sep 17 00:00:00 2001 From: Ikko Ashimine Date: Sat, 13 Feb 2021 02:45:51 +0000 Subject: cmd/link: fix typo in link_test.go specfic -> specific Change-Id: Icad0f70c77c866a1031a2929b90fef61fe92aaee GitHub-Last-Rev: f66b56491c0125f58c47f7f39410e0aeef2539be GitHub-Pull-Request: golang/go#44246 Reviewed-on: https://go-review.googlesource.com/c/go/+/291829 Reviewed-by: Ian Lance Taylor Trust: Matthew Dempsky --- src/cmd/link/link_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cmd/link/link_test.go b/src/cmd/link/link_test.go index 8153c0b31b..08ddd00a0c 100644 --- a/src/cmd/link/link_test.go +++ b/src/cmd/link/link_test.go @@ -583,7 +583,7 @@ TEXT ·alignPc(SB),NOSPLIT, $0-0 ` // TestFuncAlign verifies that the address of a function can be aligned -// with a specfic value on arm64. +// with a specific value on arm64. func TestFuncAlign(t *testing.T) { if runtime.GOARCH != "arm64" || runtime.GOOS != "linux" { t.Skip("skipping on non-linux/arm64 platform") -- cgit v1.2.3-54-g00ecf From 852ce7c2125ef7d59a24facc2b6c3df30d7f730d Mon Sep 17 00:00:00 2001 From: Rob Pike Date: Sun, 14 Feb 2021 13:22:15 +1100 Subject: cmd/go: provide a more helpful suggestion for "go vet -?" MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit For the command go vet -? the output was, usage: go vet [-n] [-x] [-vettool prog] [build flags] [vet flags] [packages] Run 'go help vet' for details. Run 'go tool vet -help' for the vet tool's flags. but "go help vet" is perfunctory at best. (That's another issue I'm working on—see https://go-review.googlesource.com/c/tools/+/291909— but vendoring is required to sort that out.) Add another line and rewrite a bit to make it actually helpful: usage: go vet [-n] [-x] [-vettool prog] [build flags] [vet flags] [packages] Run 'go help vet' for details. Run 'go tool vet help' for a full list of flags and analyzers. Run 'go tool vet -help' for an overview. Change-Id: I9d8580f0573321a57d55875ac3185988ce3eaf64 Reviewed-on: https://go-review.googlesource.com/c/go/+/291929 Trust: Rob Pike Run-TryBot: Rob Pike TryBot-Result: Go Bot Reviewed-by: Ian Lance Taylor --- src/cmd/go/internal/vet/vetflag.go | 3 ++- src/cmd/go/testdata/script/help.txt | 7 ++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/cmd/go/internal/vet/vetflag.go b/src/cmd/go/internal/vet/vetflag.go index 5bf5cf4446..b5b3c462ff 100644 --- a/src/cmd/go/internal/vet/vetflag.go +++ b/src/cmd/go/internal/vet/vetflag.go @@ -184,7 +184,8 @@ func exitWithUsage() { if vetTool != "" { cmd = vetTool } - fmt.Fprintf(os.Stderr, "Run '%s -help' for the vet tool's flags.\n", cmd) + fmt.Fprintf(os.Stderr, "Run '%s help' for a full list of flags and analyzers.\n", cmd) + fmt.Fprintf(os.Stderr, "Run '%s -help' for an overview.\n", cmd) base.SetExitStatus(2) base.Exit() diff --git a/src/cmd/go/testdata/script/help.txt b/src/cmd/go/testdata/script/help.txt index 9752ede2e3..26a0194be5 100644 --- a/src/cmd/go/testdata/script/help.txt +++ b/src/cmd/go/testdata/script/help.txt @@ -34,9 +34,10 @@ stderr 'Run ''go help mod'' for usage.' # Earlier versions of Go printed the same as 'go -h' here. # Also make sure we print the short help line. ! go vet -h -stderr 'usage: go vet' -stderr 'Run ''go help vet'' for details' -stderr 'Run ''go tool vet -help'' for the vet tool''s flags' +stderr 'usage: go vet .*' +stderr 'Run ''go help vet'' for details.' +stderr 'Run ''go tool vet help'' for a full list of flags and analyzers.' +stderr 'Run ''go tool vet -help'' for an overview.' # Earlier versions of Go printed a large document here, instead of these two # lines. -- cgit v1.2.3-54-g00ecf From 33d72fd4122a4b7e31e738d5d9283093966ec14a Mon Sep 17 00:00:00 2001 From: Ian Lance Taylor Date: Sun, 14 Feb 2021 17:21:56 -0800 Subject: doc/faq: update generics entry to reflect accepted proposal For #43651 Change-Id: Idb511f4c759d9a77de289938c19c2c1d4a542a17 Reviewed-on: https://go-review.googlesource.com/c/go/+/291990 Trust: Ian Lance Taylor Reviewed-by: Rob Pike --- doc/go_faq.html | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/doc/go_faq.html b/doc/go_faq.html index 23a3080c9b..67dc0b9bd4 100644 --- a/doc/go_faq.html +++ b/doc/go_faq.html @@ -446,8 +446,10 @@ they compensate in interesting ways for the lack of X.

Why does Go not have generic types?

-Generics may well be added at some point. We don't feel an urgency for -them, although we understand some programmers do. +A language proposal +implementing a form of generic types has been accepted for +inclusion in the language. +If all goes well it will be available in the Go 1.18 release.

-- cgit v1.2.3-54-g00ecf From 30641e36aa5b547eee48565caa3078b0a2e7c185 Mon Sep 17 00:00:00 2001 From: Ian Lance Taylor Date: Sun, 14 Feb 2021 17:14:41 -0800 Subject: internal/poll: if copy_file_range returns 0, assume it failed On current Linux kernels copy_file_range does not correctly handle files in certain special file systems, such as /proc. For those file systems it fails to copy any data and returns zero. This breaks Go's io.Copy for those files. Fix the problem by assuming that if copy_file_range returns 0 the first time it is called on a file, that that file is not supported. In that case fall back to just using read. This will force an extra system call when using io.Copy to copy a zero-sized normal file, but at least it will work correctly. For #36817 Fixes #44272 Change-Id: I02e81872cb70fda0ce5485e2ea712f219132e614 Reviewed-on: https://go-review.googlesource.com/c/go/+/291989 Trust: Ian Lance Taylor Run-TryBot: Ian Lance Taylor TryBot-Result: Go Bot Reviewed-by: Russ Cox --- src/internal/poll/copy_file_range_linux.go | 10 +++++++++- src/os/readfrom_linux_test.go | 32 ++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/internal/poll/copy_file_range_linux.go b/src/internal/poll/copy_file_range_linux.go index fc34aef4cb..01b242a4ea 100644 --- a/src/internal/poll/copy_file_range_linux.go +++ b/src/internal/poll/copy_file_range_linux.go @@ -112,7 +112,15 @@ func CopyFileRange(dst, src *FD, remain int64) (written int64, handled bool, err return 0, false, nil case nil: if n == 0 { - // src is at EOF, which means we are done. + // If we did not read any bytes at all, + // then this file may be in a file system + // where copy_file_range silently fails. + // https://lore.kernel.org/linux-fsdevel/20210126233840.GG4626@dread.disaster.area/T/#m05753578c7f7882f6e9ffe01f981bc223edef2b0 + if written == 0 { + return 0, false, nil + } + // Otherwise src is at EOF, which means + // we are done. return written, true, nil } remain -= n diff --git a/src/os/readfrom_linux_test.go b/src/os/readfrom_linux_test.go index 37047175e6..1d145dadb0 100644 --- a/src/os/readfrom_linux_test.go +++ b/src/os/readfrom_linux_test.go @@ -361,3 +361,35 @@ func (h *copyFileRangeHook) install() { func (h *copyFileRangeHook) uninstall() { *PollCopyFileRangeP = h.original } + +// On some kernels copy_file_range fails on files in /proc. +func TestProcCopy(t *testing.T) { + const cmdlineFile = "/proc/self/cmdline" + cmdline, err := os.ReadFile(cmdlineFile) + if err != nil { + t.Skipf("can't read /proc file: %v", err) + } + in, err := os.Open(cmdlineFile) + if err != nil { + t.Fatal(err) + } + defer in.Close() + outFile := filepath.Join(t.TempDir(), "cmdline") + out, err := os.Create(outFile) + if err != nil { + t.Fatal(err) + } + if _, err := io.Copy(out, in); err != nil { + t.Fatal(err) + } + if err := out.Close(); err != nil { + t.Fatal(err) + } + copy, err := os.ReadFile(outFile) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(cmdline, copy) { + t.Errorf("copy of %q got %q want %q\n", cmdlineFile, copy, cmdline) + } +} -- cgit v1.2.3-54-g00ecf From 626ef0812739ac7bb527dbdf4b0ed3a436c90901 Mon Sep 17 00:00:00 2001 From: Russ Cox Date: Fri, 12 Feb 2021 16:02:12 -0500 Subject: doc: remove install.html and install-source.html These live in x/website/content/doc now. The copies here just attract edits that have no actual effect. For #40496. For #41861. Change-Id: I2fdd7375e373949eb9a88f4cdca440b6a5d45eea Reviewed-on: https://go-review.googlesource.com/c/go/+/291709 Trust: Russ Cox Reviewed-by: Dmitri Shuralyov --- README.md | 10 +- doc/install-source.html | 777 ------------------------------------------------ doc/install.html | 315 -------------------- 3 files changed, 4 insertions(+), 1098 deletions(-) delete mode 100644 doc/install-source.html delete mode 100644 doc/install.html diff --git a/README.md b/README.md index 49231bf25d..4ca3956de8 100644 --- a/README.md +++ b/README.md @@ -19,22 +19,20 @@ BSD-style license found in the LICENSE file. Official binary distributions are available at https://golang.org/dl/. After downloading a binary release, visit https://golang.org/doc/install -or load [doc/install.html](./doc/install.html) in your web browser for installation -instructions. +for installation instructions. #### Install From Source If a binary distribution is not available for your combination of operating system and architecture, visit -https://golang.org/doc/install/source or load [doc/install-source.html](./doc/install-source.html) -in your web browser for source installation instructions. +https://golang.org/doc/install/source +for source installation instructions. ### Contributing Go is the work of thousands of contributors. We appreciate your help! -To contribute, please read the contribution guidelines: - https://golang.org/doc/contribute.html +To contribute, please read the contribution guidelines at https://golang.org/doc/contribute.html. Note that the Go project uses the issue tracker for bug reports and proposals only. See https://golang.org/wiki/Questions for a list of diff --git a/doc/install-source.html b/doc/install-source.html deleted file mode 100644 index f0a909263c..0000000000 --- a/doc/install-source.html +++ /dev/null @@ -1,777 +0,0 @@ - - -

Introduction

- -

-Go is an open source project, distributed under a -BSD-style license. -This document explains how to check out the sources, -build them on your own machine, and run them. -

- -

-Most users don't need to do this, and will instead install -from precompiled binary packages as described in -Getting Started, -a much simpler process. -If you want to help develop what goes into those precompiled -packages, though, read on. -

- -
- -

-There are two official Go compiler toolchains. -This document focuses on the gc Go -compiler and tools. -For information on how to work on gccgo, a more traditional -compiler using the GCC back end, see -Setting up and using gccgo. -

- -

-The Go compilers support the following instruction sets: - -

-
- amd64, 386 -
-
- The x86 instruction set, 64- and 32-bit. -
-
- arm64, arm -
-
- The ARM instruction set, 64-bit (AArch64) and 32-bit. -
-
- mips64, mips64le, mips, mipsle -
-
- The MIPS instruction set, big- and little-endian, 64- and 32-bit. -
-
- ppc64, ppc64le -
-
- The 64-bit PowerPC instruction set, big- and little-endian. -
-
- riscv64 -
-
- The 64-bit RISC-V instruction set. -
-
- s390x -
-
- The IBM z/Architecture. -
-
- wasm -
-
- WebAssembly. -
-
-

- -

-The compilers can target the AIX, Android, DragonFly BSD, FreeBSD, -Illumos, Linux, macOS/iOS (Darwin), NetBSD, OpenBSD, Plan 9, Solaris, -and Windows operating systems (although not all operating systems -support all architectures). -

- -

-A list of ports which are considered "first class" is available at the -first class ports -wiki page. -

- -

-The full set of supported combinations is listed in the -discussion of environment variables below. -

- -

-See the main installation page for the overall system requirements. -The following additional constraints apply to systems that can be built only from source: -

- -
    -
  • For Linux on PowerPC 64-bit, the minimum supported kernel version is 2.6.37, meaning that -Go does not support CentOS 6 on these systems. -
  • -
- -
- -

Install Go compiler binaries for bootstrap

- -

-The Go toolchain is written in Go. To build it, you need a Go compiler installed. -The scripts that do the initial build of the tools look for a "go" command -in $PATH, so as long as you have Go installed in your -system and configured in your $PATH, you are ready to build Go -from source. -Or if you prefer you can set $GOROOT_BOOTSTRAP to the -root of a Go installation to use to build the new Go toolchain; -$GOROOT_BOOTSTRAP/bin/go should be the go command to use.

- -

-There are four possible ways to obtain a bootstrap toolchain: -

- -
    -
  • Download a recent binary release of Go. -
  • Cross-compile a toolchain using a system with a working Go installation. -
  • Use gccgo. -
  • Compile a toolchain from Go 1.4, the last Go release with a compiler written in C. -
- -

-These approaches are detailed below. -

- -

Bootstrap toolchain from binary release

- -

-To use a binary release as a bootstrap toolchain, see -the downloads page or use any other -packaged Go distribution. -

- -

Bootstrap toolchain from cross-compiled source

- -

-To cross-compile a bootstrap toolchain from source, which is -necessary on systems Go 1.4 did not target (for -example, linux/ppc64le), install Go on a different system -and run bootstrap.bash. -

- -

-When run as (for example) -

- -
-$ GOOS=linux GOARCH=ppc64 ./bootstrap.bash
-
- -

-bootstrap.bash cross-compiles a toolchain for that GOOS/GOARCH -combination, leaving the resulting tree in ../../go-${GOOS}-${GOARCH}-bootstrap. -That tree can be copied to a machine of the given target type -and used as GOROOT_BOOTSTRAP to bootstrap a local build. -

- -

Bootstrap toolchain using gccgo

- -

-To use gccgo as the bootstrap toolchain, you need to arrange -for $GOROOT_BOOTSTRAP/bin/go to be the go tool that comes -as part of gccgo 5. For example on Ubuntu Vivid: -

- -
-$ sudo apt-get install gccgo-5
-$ sudo update-alternatives --set go /usr/bin/go-5
-$ GOROOT_BOOTSTRAP=/usr ./make.bash
-
- -

Bootstrap toolchain from C source code

- -

-To build a bootstrap toolchain from C source code, use -either the git branch release-branch.go1.4 or -go1.4-bootstrap-20171003.tar.gz, -which contains the Go 1.4 source code plus accumulated fixes -to keep the tools running on newer operating systems. -(Go 1.4 was the last distribution in which the toolchain was written in C.) -After unpacking the Go 1.4 source, cd to -the src subdirectory, set CGO_ENABLED=0 in -the environment, and run make.bash (or, -on Windows, make.bat). -

- -

-Once the Go 1.4 source has been unpacked into your GOROOT_BOOTSTRAP directory, -you must keep this git clone instance checked out to branch -release-branch.go1.4. Specifically, do not attempt to reuse -this git clone in the later step named "Fetch the repository." The go1.4 -bootstrap toolchain must be able to properly traverse the go1.4 sources -that it assumes are present under this repository root. -

- -

-Note that Go 1.4 does not run on all systems that later versions of Go do. -In particular, Go 1.4 does not support current versions of macOS. -On such systems, the bootstrap toolchain must be obtained using one of the other methods. -

- -

Install Git, if needed

- -

-To perform the next step you must have Git installed. (Check that you -have a git command before proceeding.) -

- -

-If you do not have a working Git installation, -follow the instructions on the -Git downloads page. -

- -

(Optional) Install a C compiler

- -

-To build a Go installation -with cgo support, which permits Go -programs to import C libraries, a C compiler such as gcc -or clang must be installed first. Do this using whatever -installation method is standard on the system. -

- -

-To build without cgo, set the environment variable -CGO_ENABLED=0 before running all.bash or -make.bash. -

- -

Fetch the repository

- -

Change to the directory where you intend to install Go, and make sure -the goroot directory does not exist. Then clone the repository -and check out the latest release tag (go1.12, -for example):

- -
-$ git clone https://go.googlesource.com/go goroot
-$ cd goroot
-$ git checkout <tag>
-
- -

-Where <tag> is the version string of the release. -

- -

Go will be installed in the directory where it is checked out. For example, -if Go is checked out in $HOME/goroot, executables will be installed -in $HOME/goroot/bin. The directory may have any name, but note -that if Go is checked out in $HOME/go, it will conflict with -the default location of $GOPATH. -See GOPATH below.

- -

-Reminder: If you opted to also compile the bootstrap binaries from source (in an -earlier section), you still need to git clone again at this point -(to checkout the latest <tag>), because you must keep your -go1.4 repository distinct. -

- - - -

If you intend to modify the go source code, and -contribute your changes -to the project, then move your repository -off the release branch, and onto the master (development) branch. -Otherwise, skip this step.

- -
-$ git checkout master
-
- -

Install Go

- -

-To build the Go distribution, run -

- -
-$ cd src
-$ ./all.bash
-
- -

-(To build under Windows use all.bat.) -

- -

-If all goes well, it will finish by printing output like: -

- -
-ALL TESTS PASSED
-
----
-Installed Go for linux/amd64 in /home/you/go.
-Installed commands in /home/you/go/bin.
-*** You need to add /home/you/go/bin to your $PATH. ***
-
- -

-where the details on the last few lines reflect the operating system, -architecture, and root directory used during the install. -

- -
-

-For more information about ways to control the build, see the discussion of -environment variables below. -all.bash (or all.bat) runs important tests for Go, -which can take more time than simply building Go. If you do not want to run -the test suite use make.bash (or make.bat) -instead. -

-
- - -

Testing your installation

- -

-Check that Go is installed correctly by building a simple program. -

- -

-Create a file named hello.go and put the following program in it: -

- -
-package main
-
-import "fmt"
-
-func main() {
-	fmt.Printf("hello, world\n")
-}
-
- -

-Then run it with the go tool: -

- -
-$ go run hello.go
-hello, world
-
- -

-If you see the "hello, world" message then Go is installed correctly. -

- -

Set up your work environment

- -

-You're almost done. -You just need to do a little more setup. -

- -

- -How to Write Go Code -Learn how to set up and use the Go tools - -

- -

-The How to Write Go Code document -provides essential setup instructions for using the Go tools. -

- - -

Install additional tools

- -

-The source code for several Go tools (including godoc) -is kept in the go.tools repository. -To install one of the tools (godoc in this case): -

- -
-$ go get golang.org/x/tools/cmd/godoc
-
- -

-To install these tools, the go get command requires -that Git be installed locally. -

- -

-You must also have a workspace (GOPATH) set up; -see How to Write Go Code for the details. -

- -

Community resources

- -

-The usual community resources such as -#go-nuts on the Freenode IRC server -and the -Go Nuts -mailing list have active developers that can help you with problems -with your installation or your development work. -For those who wish to keep up to date, -there is another mailing list, golang-checkins, -that receives a message summarizing each checkin to the Go repository. -

- -

-Bugs can be reported using the Go issue tracker. -

- - -

Keeping up with releases

- -

-New releases are announced on the -golang-announce -mailing list. -Each announcement mentions the latest release tag, for instance, -go1.9. -

- -

-To update an existing tree to the latest release, you can run: -

- -
-$ cd go/src
-$ git fetch
-$ git checkout <tag>
-$ ./all.bash
-
- -

-Where <tag> is the version string of the release. -

- - -

Optional environment variables

- -

-The Go compilation environment can be customized by environment variables. -None is required by the build, but you may wish to set some -to override the defaults. -

- -
    -
  • $GOROOT -

    -The root of the Go tree, often $HOME/go1.X. -Its value is built into the tree when it is compiled, and -defaults to the parent of the directory where all.bash was run. -There is no need to set this unless you want to switch between multiple -local copies of the repository. -

    -
  • - -
  • $GOROOT_FINAL -

    -The value assumed by installed binaries and scripts when -$GOROOT is not set explicitly. -It defaults to the value of $GOROOT. -If you want to build the Go tree in one location -but move it elsewhere after the build, set -$GOROOT_FINAL to the eventual location. -

    -
  • - -
  • $GOPATH -

    -The directory where Go projects outside the Go distribution are typically -checked out. For example, golang.org/x/tools might be checked out -to $GOPATH/src/golang.org/x/tools. Executables outside the -Go distribution are installed in $GOPATH/bin (or -$GOBIN, if set). Modules are downloaded and cached in -$GOPATH/pkg/mod. -

    - -

    The default location of $GOPATH is $HOME/go, -and it's not usually necessary to set GOPATH explicitly. However, -if you have checked out the Go distribution to $HOME/go, -you must set GOPATH to another location to avoid conflicts. -

    -
  • - -
  • $GOBIN -

    -The directory where executables outside the Go distribution are installed -using the go command. For example, -go get golang.org/x/tools/cmd/godoc downloads, builds, and -installs $GOBIN/godoc. By default, $GOBIN is -$GOPATH/bin (or $HOME/go/bin if GOPATH -is not set). After installing, you will want to add this directory to -your $PATH so you can use installed tools. -

    - -

    -Note that the Go distribution's executables are installed in -$GOROOT/bin (for executables invoked by people) or -$GOTOOLDIR (for executables invoked by the go command; -defaults to $GOROOT/pkg/$GOOS_GOARCH) instead of -$GOBIN. -

    -
  • - -
  • $GOOS and $GOARCH -

    -The name of the target operating system and compilation architecture. -These default to the values of $GOHOSTOS and -$GOHOSTARCH respectively (described below). -

  • - -

    -Choices for $GOOS are -android, darwin, dragonfly, -freebsd, illumos, ios, js, -linux, netbsd, openbsd, -plan9, solaris and windows. -

    - -

    -Choices for $GOARCH are -amd64 (64-bit x86, the most mature port), -386 (32-bit x86), arm (32-bit ARM), arm64 (64-bit ARM), -ppc64le (PowerPC 64-bit, little-endian), ppc64 (PowerPC 64-bit, big-endian), -mips64le (MIPS 64-bit, little-endian), mips64 (MIPS 64-bit, big-endian), -mipsle (MIPS 32-bit, little-endian), mips (MIPS 32-bit, big-endian), -s390x (IBM System z 64-bit, big-endian), and -wasm (WebAssembly 32-bit). -

    - -

    -The valid combinations of $GOOS and $GOARCH are: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    $GOOS $GOARCH
    aix ppc64
    android 386
    android amd64
    android arm
    android arm64
    darwin amd64
    darwin arm64
    dragonfly amd64
    freebsd 386
    freebsd amd64
    freebsd arm
    illumos amd64
    ios arm64
    js wasm
    linux 386
    linux amd64
    linux arm
    linux arm64
    linux ppc64
    linux ppc64le
    linux mips
    linux mipsle
    linux mips64
    linux mips64le
    linux riscv64
    linux s390x
    netbsd 386
    netbsd amd64
    netbsd arm
    openbsd 386
    openbsd amd64
    openbsd arm
    openbsd arm64
    plan9 386
    plan9 amd64
    plan9 arm
    solaris amd64
    windows 386
    windows amd64
    -
    - -

  • $GOHOSTOS and $GOHOSTARCH -

    -The name of the host operating system and compilation architecture. -These default to the local system's operating system and -architecture. -

    -
  • - -

    -Valid choices are the same as for $GOOS and -$GOARCH, listed above. -The specified values must be compatible with the local system. -For example, you should not set $GOHOSTARCH to -arm on an x86 system. -

    - -
  • $GO386 (for 386 only, defaults to sse2) -

    -This variable controls how gc implements floating point computations. -

    -
      -
    • GO386=softfloat: use software floating point operations; should support all x86 chips (Pentium MMX or later).
    • -
    • GO386=sse2: use SSE2 for floating point operations; has better performance but only available on Pentium 4/Opteron/Athlon 64 or later.
    • -
    -
  • - -
  • $GOARM (for arm only; default is auto-detected if building -on the target processor, 6 if not) -

    -This sets the ARM floating point co-processor architecture version the run-time -should target. If you are compiling on the target system, its value will be auto-detected. -

    -
      -
    • GOARM=5: use software floating point; when CPU doesn't have VFP co-processor
    • -
    • GOARM=6: use VFPv1 only; default if cross compiling; usually ARM11 or better cores (VFPv2 or better is also supported)
    • -
    • GOARM=7: use VFPv3; usually Cortex-A cores
    • -
    -

    -If in doubt, leave this variable unset, and adjust it if required -when you first run the Go executable. -The GoARM page -on the Go community wiki -contains further details regarding Go's ARM support. -

    -
  • - -
  • $GOMIPS (for mips and mipsle only)
    $GOMIPS64 (for mips64 and mips64le only) -

    - These variables set whether to use floating point instructions. Set to "hardfloat" to use floating point instructions; this is the default. Set to "softfloat" to use soft floating point. -

    -
  • - -
  • $GOPPC64 (for ppc64 and ppc64le only) -

    -This variable sets the processor level (i.e. Instruction Set Architecture version) -for which the compiler will target. The default is power8. -

    -
      -
    • GOPPC64=power8: generate ISA v2.07 instructions
    • -
    • GOPPC64=power9: generate ISA v3.00 instructions
    • -
    -
  • - - -
  • $GOWASM (for wasm only) -

    - This variable is a comma separated list of experimental WebAssembly features that the compiled WebAssembly binary is allowed to use. - The default is to use no experimental features. -

    - -
  • - -
- -

-Note that $GOARCH and $GOOS identify the -target environment, not the environment you are running on. -In effect, you are always cross-compiling. -By architecture, we mean the kind of binaries -that the target environment can run: -an x86-64 system running a 32-bit-only operating system -must set GOARCH to 386, -not amd64. -

- -

-If you choose to override the defaults, -set these variables in your shell profile ($HOME/.bashrc, -$HOME/.profile, or equivalent). The settings might look -something like this: -

- -
-export GOARCH=amd64
-export GOOS=linux
-
- -

-although, to reiterate, none of these variables needs to be set to build, -install, and develop the Go tree. -

diff --git a/doc/install.html b/doc/install.html deleted file mode 100644 index 706d66c007..0000000000 --- a/doc/install.html +++ /dev/null @@ -1,315 +0,0 @@ - - -
- -

Download the Go distribution

- -

- -Download Go -Click here to visit the downloads page - -

- -

-Official binary -distributions are available for the FreeBSD (release 10-STABLE and above), -Linux, macOS (10.11 and above), and Windows operating systems and -the 32-bit (386) and 64-bit (amd64) x86 processor -architectures. -

- -

-If a binary distribution is not available for your combination of operating -system and architecture, try -installing from source or -installing gccgo instead of gc. -

- - -

System requirements

- -

-Go binary distributions are available for these supported operating systems and architectures. -Please ensure your system meets these requirements before proceeding. -If your OS or architecture is not on the list, you may be able to -install from source or -use gccgo instead. -

- - - - - - - - - - - - -
Operating systemArchitecturesNotes

FreeBSD 10.3 or later amd64, 386 Debian GNU/kFreeBSD not supported
Linux 2.6.23 or later with glibc amd64, 386, arm, arm64,
s390x, ppc64le
CentOS/RHEL 5.x not supported.
Install from source for other libc.
macOS 10.11 or later amd64 use the clang or gcc that comes with Xcode for cgo support
Windows 7, Server 2008R2 or later amd64, 386 use MinGW (386) or MinGW-W64 (amd64) gcc.
No need for cygwin or msys.
- -

-A C compiler is required only if you plan to use -cgo.
-You only need to install the command line tools for -Xcode. If you have already -installed Xcode 4.3+, you can install it from the Components tab of the -Downloads preferences panel. -

- -
- - -

Install the Go tools

- -

-If you are upgrading from an older version of Go you must -first remove the existing version. -

- -
- -

Linux, macOS, and FreeBSD tarballs

- -

-Download the archive -and extract it into /usr/local, creating a Go tree in -/usr/local/go. For example: -

- -
-tar -C /usr/local -xzf go$VERSION.$OS-$ARCH.tar.gz
-
- -

-Choose the archive file appropriate for your installation. -For instance, if you are installing Go version 1.2.1 for 64-bit x86 on Linux, -the archive you want is called go1.2.1.linux-amd64.tar.gz. -

- -

-(Typically these commands must be run as root or through sudo.) -

- -

-Add /usr/local/go/bin to the PATH environment -variable. You can do this by adding this line to your /etc/profile -(for a system-wide installation) or $HOME/.profile: -

- -
-export PATH=$PATH:/usr/local/go/bin
-
- -

-Note: changes made to a profile file may not apply until the -next time you log into your computer. -To apply the changes immediately, just run the shell commands directly -or execute them from the profile using a command such as -source $HOME/.profile. -

- -
- -
- -

macOS package installer

- -

-Download the package file, -open it, and follow the prompts to install the Go tools. -The package installs the Go distribution to /usr/local/go. -

- -

-The package should put the /usr/local/go/bin directory in your -PATH environment variable. You may need to restart any open -Terminal sessions for the change to take effect. -

- -
- -
- -

Windows

- -

-The Go project provides two installation options for Windows users -(besides installing from source): -a zip archive that requires you to set some environment variables and an -MSI installer that configures your installation automatically. -

- -
- -

MSI installer

- -

-Open the MSI file -and follow the prompts to install the Go tools. -By default, the installer puts the Go distribution in c:\Go. -

- -

-The installer should put the c:\Go\bin directory in your -PATH environment variable. You may need to restart any open -command prompts for the change to take effect. -

- -
- -
- -

Zip archive

- -

-Download the zip file and extract it into the directory of your choice (we suggest c:\Go). -

- -

-Add the bin subdirectory of your Go root (for example, c:\Go\bin) to your PATH environment variable. -

- -
- -

Setting environment variables under Windows

- -

-Under Windows, you may set environment variables through the "Environment -Variables" button on the "Advanced" tab of the "System" control panel. Some -versions of Windows provide this control panel through the "Advanced System -Settings" option inside the "System" control panel. -

- -
- - -

Test your installation

- -

-Check that Go is installed correctly by building a simple program, as follows. -

- -

-Create a file named hello.go that looks like: -

- -
-package main
-
-import "fmt"
-
-func main() {
-	fmt.Printf("hello, world\n")
-}
-
- -

-Then build it with the go tool: -

- -
-$ go build hello.go
-
- -
-C:\Users\Gopher\go\src\hello> go build hello.go
-
- -

-The command above will build an executable named -hellohello.exe -in the current directory alongside your source code. -Execute it to see the greeting: -

- -
-$ ./hello
-hello, world
-
- -
-C:\Users\Gopher\go\src\hello> hello
-hello, world
-
- -

-If you see the "hello, world" message then your Go installation is working. -

- -

-Before rushing off to write Go code please read the -How to Write Go Code document, -which describes some essential concepts about using the Go tools. -

- - -

Installing extra Go versions

- -

-It may be useful to have multiple Go versions installed on the same machine, for -example, to ensure that a package's tests pass on multiple Go versions. -Once you have one Go version installed, you can install another (such as 1.10.7) -as follows: -

- -
-$ go get golang.org/dl/go1.10.7
-$ go1.10.7 download
-
- -

-The newly downloaded version can be used like go: -

- -
-$ go1.10.7 version
-go version go1.10.7 linux/amd64
-
- -

-All Go versions available via this method are listed on -the download page. -You can find where each of these extra Go versions is installed by looking -at its GOROOT; for example, go1.10.7 env GOROOT. -To uninstall a downloaded version, just remove its GOROOT directory -and the goX.Y.Z binary. -

- - -

Uninstalling Go

- -

-To remove an existing Go installation from your system delete the -go directory. This is usually /usr/local/go -under Linux, macOS, and FreeBSD or c:\Go -under Windows. -

- -

-You should also remove the Go bin directory from your -PATH environment variable. -Under Linux and FreeBSD you should edit /etc/profile or -$HOME/.profile. -If you installed Go with the macOS package then you -should remove the /etc/paths.d/go file. -Windows users should read the section about setting -environment variables under Windows. -

- - -

Getting help

- -

- For help, see the list of Go mailing lists, forums, and places to chat. -

- -

- Report bugs either by running “go bug”, or - manually at the Go issue tracker. -

-- cgit v1.2.3-54-g00ecf From 0cb3415154ff354b42db1d65073e9be71abcc970 Mon Sep 17 00:00:00 2001 From: Russ Cox Date: Fri, 12 Feb 2021 16:16:25 -0500 Subject: doc: remove all docs not tied to distribution They have moved to x/website in CL 291693. The docs that are left are the ones that are edited at the same time as development in this repository and are tied to the specific version of Go being developed. Those are: - the language spec - the memory model - the assembler manual - the current release's release notes Change-Id: I437c4d33ada1b1716b1919c3c939c2cacf407e83 Reviewed-on: https://go-review.googlesource.com/c/go/+/291711 Trust: Russ Cox Trust: Dmitri Shuralyov Reviewed-by: Dmitri Shuralyov --- doc/articles/go_command.html | 254 --- doc/articles/index.html | 8 - doc/articles/race_detector.html | 440 ---- doc/articles/wiki/edit.html | 6 - doc/articles/wiki/final-noclosure.go | 105 - doc/articles/wiki/final-noerror.go | 56 - doc/articles/wiki/final-parsetemplate.go | 94 - doc/articles/wiki/final-template.go | 68 - doc/articles/wiki/final.go | 92 - doc/articles/wiki/final_test.go | 24 - doc/articles/wiki/go.mod | 3 - doc/articles/wiki/http-sample.go | 18 - doc/articles/wiki/index.html | 741 ------ doc/articles/wiki/notemplate.go | 59 - doc/articles/wiki/part1-noerror.go | 35 - doc/articles/wiki/part1.go | 38 - doc/articles/wiki/part2.go | 44 - doc/articles/wiki/part3-errorhandling.go | 76 - doc/articles/wiki/part3.go | 60 - doc/articles/wiki/test_Test.txt.good | 1 - doc/articles/wiki/test_edit.good | 6 - doc/articles/wiki/test_view.good | 5 - doc/articles/wiki/view.html | 5 - doc/articles/wiki/wiki_test.go | 165 -- doc/cmd.html | 100 - doc/codewalk/codewalk.css | 234 -- doc/codewalk/codewalk.js | 305 --- doc/codewalk/codewalk.xml | 124 - doc/codewalk/codewalk_test.go | 52 - doc/codewalk/functions.xml | 105 - doc/codewalk/markov.go | 130 -- doc/codewalk/markov.xml | 307 --- doc/codewalk/pig.go | 121 - doc/codewalk/popout.png | Bin 213 -> 0 bytes doc/codewalk/sharemem.xml | 181 -- doc/codewalk/urlpoll.go | 116 - doc/contribute.html | 1294 ----------- doc/debugging_with_gdb.html | 554 ----- doc/diagnostics.html | 472 ---- doc/editors.html | 33 - doc/effective_go.html | 3673 ------------------------------ doc/gccgo_contribute.html | 112 - doc/gccgo_install.html | 533 ----- doc/go-logo-black.png | Bin 8843 -> 0 bytes doc/go-logo-blue.png | Bin 9360 -> 0 bytes doc/go-logo-white.png | Bin 21469 -> 0 bytes doc/go1.1.html | 1099 --------- doc/go1.10.html | 1448 ------------ doc/go1.11.html | 934 -------- doc/go1.12.html | 949 -------- doc/go1.13.html | 1066 --------- doc/go1.14.html | 924 -------- doc/go1.15.html | 1064 --------- doc/go1.2.html | 979 -------- doc/go1.3.html | 608 ----- doc/go1.4.html | 896 -------- doc/go1.5.html | 1310 ----------- doc/go1.6.html | 923 -------- doc/go1.7.html | 1281 ----------- doc/go1.8.html | 1666 -------------- doc/go1.9.html | 1024 --------- doc/go1.html | 2038 ----------------- doc/go1compat.html | 202 -- doc/go_faq.html | 2477 -------------------- doc/gopher/README | 3 - doc/gopher/appenginegopher.jpg | Bin 135882 -> 0 bytes doc/gopher/appenginegophercolor.jpg | Bin 162023 -> 0 bytes doc/gopher/appenginelogo.gif | Bin 2105 -> 0 bytes doc/gopher/biplane.jpg | Bin 203420 -> 0 bytes doc/gopher/bumper.png | Bin 276215 -> 0 bytes doc/gopher/bumper192x108.png | Bin 8432 -> 0 bytes doc/gopher/bumper320x180.png | Bin 15098 -> 0 bytes doc/gopher/bumper480x270.png | Bin 26509 -> 0 bytes doc/gopher/bumper640x360.png | Bin 42013 -> 0 bytes doc/gopher/doc.png | Bin 4395 -> 0 bytes doc/gopher/favicon.svg | 238 -- doc/gopher/fiveyears.jpg | Bin 220526 -> 0 bytes doc/gopher/frontpage.png | Bin 17668 -> 0 bytes doc/gopher/gopherbw.png | Bin 171323 -> 0 bytes doc/gopher/gophercolor.png | Bin 169406 -> 0 bytes doc/gopher/gophercolor16x16.png | Bin 739 -> 0 bytes doc/gopher/help.png | Bin 5729 -> 0 bytes doc/gopher/modelsheet.jpg | Bin 85880 -> 0 bytes doc/gopher/pencil/gopherhat.jpg | Bin 129627 -> 0 bytes doc/gopher/pencil/gopherhelmet.jpg | Bin 151965 -> 0 bytes doc/gopher/pencil/gophermega.jpg | Bin 122348 -> 0 bytes doc/gopher/pencil/gopherrunning.jpg | Bin 86299 -> 0 bytes doc/gopher/pencil/gopherswim.jpg | Bin 158593 -> 0 bytes doc/gopher/pencil/gopherswrench.jpg | Bin 231095 -> 0 bytes doc/gopher/pkg.png | Bin 5409 -> 0 bytes doc/gopher/project.png | Bin 8042 -> 0 bytes doc/gopher/ref.png | Bin 5895 -> 0 bytes doc/gopher/run.png | Bin 9220 -> 0 bytes doc/gopher/talks.png | Bin 4877 -> 0 bytes doc/help.html | 96 - doc/ie.css | 1 - doc/play/fib.go | 19 - doc/play/hello.go | 9 - doc/play/life.go | 113 - doc/play/peano.go | 88 - doc/play/pi.go | 34 - doc/play/sieve.go | 36 - doc/play/solitaire.go | 117 - doc/play/tree.go | 100 - doc/progs/cgo1.go | 22 - doc/progs/cgo2.go | 22 - doc/progs/cgo3.go | 18 - doc/progs/cgo4.go | 18 - doc/progs/defer.go | 64 - doc/progs/defer2.go | 58 - doc/progs/eff_bytesize.go | 47 - doc/progs/eff_qr.go | 50 - doc/progs/eff_sequence.go | 49 - doc/progs/eff_unused1.go | 16 - doc/progs/eff_unused2.go | 20 - doc/progs/error.go | 127 -- doc/progs/error2.go | 54 - doc/progs/error3.go | 63 - doc/progs/error4.go | 74 - doc/progs/go1.go | 245 -- doc/progs/gobs1.go | 22 - doc/progs/gobs2.go | 43 - doc/progs/image_draw.go | 142 -- doc/progs/image_package1.go | 15 - doc/progs/image_package2.go | 16 - doc/progs/image_package3.go | 15 - doc/progs/image_package4.go | 16 - doc/progs/image_package5.go | 17 - doc/progs/image_package6.go | 17 - doc/progs/interface.go | 62 - doc/progs/interface2.go | 132 -- doc/progs/json1.go | 88 - doc/progs/json2.go | 42 - doc/progs/json3.go | 73 - doc/progs/json4.go | 45 - doc/progs/json5.go | 31 - doc/progs/run.go | 229 -- doc/progs/slices.go | 63 - doc/progs/timeout1.go | 29 - doc/progs/timeout2.go | 28 - doc/share.png | Bin 2993 -> 0 bytes doc/tos.html | 11 - src/cmd/dist/test.go | 8 - 143 files changed, 34682 deletions(-) delete mode 100644 doc/articles/go_command.html delete mode 100644 doc/articles/index.html delete mode 100644 doc/articles/race_detector.html delete mode 100644 doc/articles/wiki/edit.html delete mode 100644 doc/articles/wiki/final-noclosure.go delete mode 100644 doc/articles/wiki/final-noerror.go delete mode 100644 doc/articles/wiki/final-parsetemplate.go delete mode 100644 doc/articles/wiki/final-template.go delete mode 100644 doc/articles/wiki/final.go delete mode 100644 doc/articles/wiki/final_test.go delete mode 100644 doc/articles/wiki/go.mod delete mode 100644 doc/articles/wiki/http-sample.go delete mode 100644 doc/articles/wiki/index.html delete mode 100644 doc/articles/wiki/notemplate.go delete mode 100644 doc/articles/wiki/part1-noerror.go delete mode 100644 doc/articles/wiki/part1.go delete mode 100644 doc/articles/wiki/part2.go delete mode 100644 doc/articles/wiki/part3-errorhandling.go delete mode 100644 doc/articles/wiki/part3.go delete mode 100644 doc/articles/wiki/test_Test.txt.good delete mode 100644 doc/articles/wiki/test_edit.good delete mode 100644 doc/articles/wiki/test_view.good delete mode 100644 doc/articles/wiki/view.html delete mode 100644 doc/articles/wiki/wiki_test.go delete mode 100644 doc/cmd.html delete mode 100644 doc/codewalk/codewalk.css delete mode 100644 doc/codewalk/codewalk.js delete mode 100644 doc/codewalk/codewalk.xml delete mode 100644 doc/codewalk/codewalk_test.go delete mode 100644 doc/codewalk/functions.xml delete mode 100644 doc/codewalk/markov.go delete mode 100644 doc/codewalk/markov.xml delete mode 100644 doc/codewalk/pig.go delete mode 100644 doc/codewalk/popout.png delete mode 100644 doc/codewalk/sharemem.xml delete mode 100644 doc/codewalk/urlpoll.go delete mode 100644 doc/contribute.html delete mode 100644 doc/debugging_with_gdb.html delete mode 100644 doc/diagnostics.html delete mode 100644 doc/editors.html delete mode 100644 doc/effective_go.html delete mode 100644 doc/gccgo_contribute.html delete mode 100644 doc/gccgo_install.html delete mode 100644 doc/go-logo-black.png delete mode 100644 doc/go-logo-blue.png delete mode 100644 doc/go-logo-white.png delete mode 100644 doc/go1.1.html delete mode 100644 doc/go1.10.html delete mode 100644 doc/go1.11.html delete mode 100644 doc/go1.12.html delete mode 100644 doc/go1.13.html delete mode 100644 doc/go1.14.html delete mode 100644 doc/go1.15.html delete mode 100644 doc/go1.2.html delete mode 100644 doc/go1.3.html delete mode 100644 doc/go1.4.html delete mode 100644 doc/go1.5.html delete mode 100644 doc/go1.6.html delete mode 100644 doc/go1.7.html delete mode 100644 doc/go1.8.html delete mode 100644 doc/go1.9.html delete mode 100644 doc/go1.html delete mode 100644 doc/go1compat.html delete mode 100644 doc/go_faq.html delete mode 100644 doc/gopher/README delete mode 100644 doc/gopher/appenginegopher.jpg delete mode 100644 doc/gopher/appenginegophercolor.jpg delete mode 100644 doc/gopher/appenginelogo.gif delete mode 100644 doc/gopher/biplane.jpg delete mode 100644 doc/gopher/bumper.png delete mode 100644 doc/gopher/bumper192x108.png delete mode 100644 doc/gopher/bumper320x180.png delete mode 100644 doc/gopher/bumper480x270.png delete mode 100644 doc/gopher/bumper640x360.png delete mode 100644 doc/gopher/doc.png delete mode 100644 doc/gopher/favicon.svg delete mode 100644 doc/gopher/fiveyears.jpg delete mode 100644 doc/gopher/frontpage.png delete mode 100644 doc/gopher/gopherbw.png delete mode 100644 doc/gopher/gophercolor.png delete mode 100644 doc/gopher/gophercolor16x16.png delete mode 100644 doc/gopher/help.png delete mode 100644 doc/gopher/modelsheet.jpg delete mode 100644 doc/gopher/pencil/gopherhat.jpg delete mode 100644 doc/gopher/pencil/gopherhelmet.jpg delete mode 100644 doc/gopher/pencil/gophermega.jpg delete mode 100644 doc/gopher/pencil/gopherrunning.jpg delete mode 100644 doc/gopher/pencil/gopherswim.jpg delete mode 100644 doc/gopher/pencil/gopherswrench.jpg delete mode 100644 doc/gopher/pkg.png delete mode 100644 doc/gopher/project.png delete mode 100644 doc/gopher/ref.png delete mode 100644 doc/gopher/run.png delete mode 100644 doc/gopher/talks.png delete mode 100644 doc/help.html delete mode 100644 doc/ie.css delete mode 100644 doc/play/fib.go delete mode 100644 doc/play/hello.go delete mode 100644 doc/play/life.go delete mode 100644 doc/play/peano.go delete mode 100644 doc/play/pi.go delete mode 100644 doc/play/sieve.go delete mode 100644 doc/play/solitaire.go delete mode 100644 doc/play/tree.go delete mode 100644 doc/progs/cgo1.go delete mode 100644 doc/progs/cgo2.go delete mode 100644 doc/progs/cgo3.go delete mode 100644 doc/progs/cgo4.go delete mode 100644 doc/progs/defer.go delete mode 100644 doc/progs/defer2.go delete mode 100644 doc/progs/eff_bytesize.go delete mode 100644 doc/progs/eff_qr.go delete mode 100644 doc/progs/eff_sequence.go delete mode 100644 doc/progs/eff_unused1.go delete mode 100644 doc/progs/eff_unused2.go delete mode 100644 doc/progs/error.go delete mode 100644 doc/progs/error2.go delete mode 100644 doc/progs/error3.go delete mode 100644 doc/progs/error4.go delete mode 100644 doc/progs/go1.go delete mode 100644 doc/progs/gobs1.go delete mode 100644 doc/progs/gobs2.go delete mode 100644 doc/progs/image_draw.go delete mode 100644 doc/progs/image_package1.go delete mode 100644 doc/progs/image_package2.go delete mode 100644 doc/progs/image_package3.go delete mode 100644 doc/progs/image_package4.go delete mode 100644 doc/progs/image_package5.go delete mode 100644 doc/progs/image_package6.go delete mode 100644 doc/progs/interface.go delete mode 100644 doc/progs/interface2.go delete mode 100644 doc/progs/json1.go delete mode 100644 doc/progs/json2.go delete mode 100644 doc/progs/json3.go delete mode 100644 doc/progs/json4.go delete mode 100644 doc/progs/json5.go delete mode 100644 doc/progs/run.go delete mode 100644 doc/progs/slices.go delete mode 100644 doc/progs/timeout1.go delete mode 100644 doc/progs/timeout2.go delete mode 100644 doc/share.png delete mode 100644 doc/tos.html diff --git a/doc/articles/go_command.html b/doc/articles/go_command.html deleted file mode 100644 index 5b6fd4d24b..0000000000 --- a/doc/articles/go_command.html +++ /dev/null @@ -1,254 +0,0 @@ - - -

The Go distribution includes a command, named -"go", that -automates the downloading, building, installation, and testing of Go packages -and commands. This document talks about why we wrote a new command, what it -is, what it's not, and how to use it.

- -

Motivation

- -

You might have seen early Go talks in which Rob Pike jokes that the idea -for Go arose while waiting for a large Google server to compile. That -really was the motivation for Go: to build a language that worked well -for building the large software that Google writes and runs. It was -clear from the start that such a language must provide a way to -express dependencies between code libraries clearly, hence the package -grouping and the explicit import blocks. It was also clear from the -start that you might want arbitrary syntax for describing the code -being imported; this is why import paths are string literals.

- -

An explicit goal for Go from the beginning was to be able to build Go -code using only the information found in the source itself, not -needing to write a makefile or one of the many modern replacements for -makefiles. If Go needed a configuration file to explain how to build -your program, then Go would have failed.

- -

At first, there was no Go compiler, and the initial development -focused on building one and then building libraries for it. For -expedience, we postponed the automation of building Go code by using -make and writing makefiles. When compiling a single package involved -multiple invocations of the Go compiler, we even used a program to -write the makefiles for us. You can find it if you dig through the -repository history.

- -

The purpose of the new go command is our return to this ideal, that Go -programs should compile without configuration or additional effort on -the part of the developer beyond writing the necessary import -statements.

- -

Configuration versus convention

- -

The way to achieve the simplicity of a configuration-free system is to -establish conventions. The system works only to the extent that those conventions -are followed. When we first launched Go, many people published packages that -had to be installed in certain places, under certain names, using certain build -tools, in order to be used. That's understandable: that's the way it works in -most other languages. Over the last few years we consistently reminded people -about the goinstall command -(now replaced by go get) -and its conventions: first, that the import path is derived in a known way from -the URL of the source code; second, that the place to store the sources in -the local file system is derived in a known way from the import path; third, -that each directory in a source tree corresponds to a single package; and -fourth, that the package is built using only information in the source code. -Today, the vast majority of packages follow these conventions. -The Go ecosystem is simpler and more powerful as a result.

- -

We received many requests to allow a makefile in a package directory to -provide just a little extra configuration beyond what's in the source code. -But that would have introduced new rules. Because we did not accede to such -requests, we were able to write the go command and eliminate our use of make -or any other build system.

- -

It is important to understand that the go command is not a general -build tool. It cannot be configured and it does not attempt to build -anything but Go packages. These are important simplifying -assumptions: they simplify not only the implementation but also, more -important, the use of the tool itself.

- -

Go's conventions

- -

The go command requires that code adheres to a few key, -well-established conventions.

- -

First, the import path is derived in a known way from the URL of the -source code. For Bitbucket, GitHub, Google Code, and Launchpad, the -root directory of the repository is identified by the repository's -main URL, without the http:// prefix. Subdirectories are named by -adding to that path. -For example, the Go example programs are obtained by running

- -
-git clone https://github.com/golang/example
-
- -

and thus the import path for the root directory of that repository is -"github.com/golang/example". -The stringutil -package is stored in a subdirectory, so its import path is -"github.com/golang/example/stringutil".

- -

These paths are on the long side, but in exchange we get an -automatically managed name space for import paths and the ability for -a tool like the go command to look at an unfamiliar import path and -deduce where to obtain the source code.

- -

Second, the place to store sources in the local file system is derived -in a known way from the import path, specifically -$GOPATH/src/<import-path>. -If unset, $GOPATH defaults to a subdirectory -named go in the user's home directory. -If $GOPATH is set to a list of paths, the go command tries -<dir>/src/<import-path> for each of the directories in -that list. -

- -

Each of those trees contains, by convention, a top-level directory named -"bin", for holding compiled executables, and a top-level directory -named "pkg", for holding compiled packages that can be imported, -and the "src" directory, for holding package source files. -Imposing this structure lets us keep each of these directory trees -self-contained: the compiled form and the sources are always near each -other.

- -

These naming conventions also let us work in the reverse direction, -from a directory name to its import path. This mapping is important -for many of the go command's subcommands, as we'll see below.

- -

Third, each directory in a source tree corresponds to a single -package. By restricting a directory to a single package, we don't have -to create hybrid import paths that specify first the directory and -then the package within that directory. Also, most file management -tools and UIs work on directories as fundamental units. Tying the -fundamental Go unit—the package—to file system structure means -that file system tools become Go package tools. Copying, moving, or -deleting a package corresponds to copying, moving, or deleting a -directory.

- -

Fourth, each package is built using only the information present in -the source files. This makes it much more likely that the tool will -be able to adapt to changing build environments and conditions. For -example, if we allowed extra configuration such as compiler flags or -command line recipes, then that configuration would need to be updated -each time the build tools changed; it would also be inherently tied -to the use of a specific toolchain.

- -

Getting started with the go command

- -

Finally, a quick tour of how to use the go command. -As mentioned above, the default $GOPATH on Unix is $HOME/go. -We'll store our programs there. -To use a different location, you can set $GOPATH; -see How to Write Go Code for details. - -

We first add some source code. Suppose we want to use -the indexing library from the codesearch project along with a left-leaning -red-black tree. We can install both with the "go get" -subcommand:

- -
-$ go get github.com/google/codesearch/index
-$ go get github.com/petar/GoLLRB/llrb
-$
-
- -

Both of these projects are now downloaded and installed into $HOME/go, -which contains the two directories -src/github.com/google/codesearch/index/ and -src/github.com/petar/GoLLRB/llrb/, along with the compiled -packages (in pkg/) for those libraries and their dependencies.

- -

Because we used version control systems (Mercurial and Git) to check -out the sources, the source tree also contains the other files in the -corresponding repositories, such as related packages. The "go list" -subcommand lists the import paths corresponding to its arguments, and -the pattern "./..." means start in the current directory -("./") and find all packages below that directory -("..."):

- -
-$ cd $HOME/go/src
-$ go list ./...
-github.com/google/codesearch/cmd/cgrep
-github.com/google/codesearch/cmd/cindex
-github.com/google/codesearch/cmd/csearch
-github.com/google/codesearch/index
-github.com/google/codesearch/regexp
-github.com/google/codesearch/sparse
-github.com/petar/GoLLRB/example
-github.com/petar/GoLLRB/llrb
-$
-
- -

We can also test those packages:

- -
-$ go test ./...
-?   	github.com/google/codesearch/cmd/cgrep	[no test files]
-?   	github.com/google/codesearch/cmd/cindex	[no test files]
-?   	github.com/google/codesearch/cmd/csearch	[no test files]
-ok  	github.com/google/codesearch/index	0.203s
-ok  	github.com/google/codesearch/regexp	0.017s
-?   	github.com/google/codesearch/sparse	[no test files]
-?       github.com/petar/GoLLRB/example          [no test files]
-ok      github.com/petar/GoLLRB/llrb             0.231s
-$
-
- -

If a go subcommand is invoked with no paths listed, it operates on the -current directory:

- -
-$ cd github.com/google/codesearch/regexp
-$ go list
-github.com/google/codesearch/regexp
-$ go test -v
-=== RUN   TestNstateEnc
---- PASS: TestNstateEnc (0.00s)
-=== RUN   TestMatch
---- PASS: TestMatch (0.00s)
-=== RUN   TestGrep
---- PASS: TestGrep (0.00s)
-PASS
-ok  	github.com/google/codesearch/regexp	0.018s
-$ go install
-$
-
- -

That "go install" subcommand installs the latest copy of the -package into the pkg directory. Because the go command can analyze the -dependency graph, "go install" also installs any packages that -this package imports but that are out of date, recursively.

- -

Notice that "go install" was able to determine the name of the -import path for the package in the current directory, because of the convention -for directory naming. It would be a little more convenient if we could pick -the name of the directory where we kept source code, and we probably wouldn't -pick such a long name, but that ability would require additional configuration -and complexity in the tool. Typing an extra directory name or two is a small -price to pay for the increased simplicity and power.

- -

Limitations

- -

As mentioned above, the go command is not a general-purpose build -tool. -In particular, it does not have any facility for generating Go -source files during a build, although it does provide -go -generate, -which can automate the creation of Go files before the build. -For more advanced build setups, you may need to write a -makefile (or a configuration file for the build tool of your choice) -to run whatever tool creates the Go files and then check those generated source files -into your repository. This is more work for you, the package author, -but it is significantly less work for your users, who can use -"go get" without needing to obtain and build -any additional tools.

- -

More information

- -

For more information, read How to Write Go Code -and see the go command documentation.

diff --git a/doc/articles/index.html b/doc/articles/index.html deleted file mode 100644 index 9ddd669731..0000000000 --- a/doc/articles/index.html +++ /dev/null @@ -1,8 +0,0 @@ - - -

-See the Documents page and the -Blog index for a complete list of Go articles. -

diff --git a/doc/articles/race_detector.html b/doc/articles/race_detector.html deleted file mode 100644 index 09188c15d5..0000000000 --- a/doc/articles/race_detector.html +++ /dev/null @@ -1,440 +0,0 @@ - - -

Introduction

- -

-Data races are among the most common and hardest to debug types of bugs in concurrent systems. -A data race occurs when two goroutines access the same variable concurrently and at least one of the accesses is a write. -See the The Go Memory Model for details. -

- -

-Here is an example of a data race that can lead to crashes and memory corruption: -

- -
-func main() {
-	c := make(chan bool)
-	m := make(map[string]string)
-	go func() {
-		m["1"] = "a" // First conflicting access.
-		c <- true
-	}()
-	m["2"] = "b" // Second conflicting access.
-	<-c
-	for k, v := range m {
-		fmt.Println(k, v)
-	}
-}
-
- -

Usage

- -

-To help diagnose such bugs, Go includes a built-in data race detector. -To use it, add the -race flag to the go command: -

- -
-$ go test -race mypkg    // to test the package
-$ go run -race mysrc.go  // to run the source file
-$ go build -race mycmd   // to build the command
-$ go install -race mypkg // to install the package
-
- -

Report Format

- -

-When the race detector finds a data race in the program, it prints a report. -The report contains stack traces for conflicting accesses, as well as stacks where the involved goroutines were created. -Here is an example: -

- -
-WARNING: DATA RACE
-Read by goroutine 185:
-  net.(*pollServer).AddFD()
-      src/net/fd_unix.go:89 +0x398
-  net.(*pollServer).WaitWrite()
-      src/net/fd_unix.go:247 +0x45
-  net.(*netFD).Write()
-      src/net/fd_unix.go:540 +0x4d4
-  net.(*conn).Write()
-      src/net/net.go:129 +0x101
-  net.func·060()
-      src/net/timeout_test.go:603 +0xaf
-
-Previous write by goroutine 184:
-  net.setWriteDeadline()
-      src/net/sockopt_posix.go:135 +0xdf
-  net.setDeadline()
-      src/net/sockopt_posix.go:144 +0x9c
-  net.(*conn).SetDeadline()
-      src/net/net.go:161 +0xe3
-  net.func·061()
-      src/net/timeout_test.go:616 +0x3ed
-
-Goroutine 185 (running) created at:
-  net.func·061()
-      src/net/timeout_test.go:609 +0x288
-
-Goroutine 184 (running) created at:
-  net.TestProlongTimeout()
-      src/net/timeout_test.go:618 +0x298
-  testing.tRunner()
-      src/testing/testing.go:301 +0xe8
-
- -

Options

- -

-The GORACE environment variable sets race detector options. -The format is: -

- -
-GORACE="option1=val1 option2=val2"
-
- -

-The options are: -

- -
    -
  • -log_path (default stderr): The race detector writes -its report to a file named log_path.pid. -The special names stdout -and stderr cause reports to be written to standard output and -standard error, respectively. -
  • - -
  • -exitcode (default 66): The exit status to use when -exiting after a detected race. -
  • - -
  • -strip_path_prefix (default ""): Strip this prefix -from all reported file paths, to make reports more concise. -
  • - -
  • -history_size (default 1): The per-goroutine memory -access history is 32K * 2**history_size elements. -Increasing this value can avoid a "failed to restore the stack" error in reports, at the -cost of increased memory usage. -
  • - -
  • -halt_on_error (default 0): Controls whether the program -exits after reporting first data race. -
  • - -
  • -atexit_sleep_ms (default 1000): Amount of milliseconds -to sleep in the main goroutine before exiting. -
  • -
- -

-Example: -

- -
-$ GORACE="log_path=/tmp/race/report strip_path_prefix=/my/go/sources/" go test -race
-
- -

Excluding Tests

- -

-When you build with -race flag, the go command defines additional -build tag race. -You can use the tag to exclude some code and tests when running the race detector. -Some examples: -

- -
-// +build !race
-
-package foo
-
-// The test contains a data race. See issue 123.
-func TestFoo(t *testing.T) {
-	// ...
-}
-
-// The test fails under the race detector due to timeouts.
-func TestBar(t *testing.T) {
-	// ...
-}
-
-// The test takes too long under the race detector.
-func TestBaz(t *testing.T) {
-	// ...
-}
-
- -

How To Use

- -

-To start, run your tests using the race detector (go test -race). -The race detector only finds races that happen at runtime, so it can't find -races in code paths that are not executed. -If your tests have incomplete coverage, -you may find more races by running a binary built with -race under a realistic -workload. -

- -

Typical Data Races

- -

-Here are some typical data races. All of them can be detected with the race detector. -

- -

Race on loop counter

- -
-func main() {
-	var wg sync.WaitGroup
-	wg.Add(5)
-	for i := 0; i < 5; i++ {
-		go func() {
-			fmt.Println(i) // Not the 'i' you are looking for.
-			wg.Done()
-		}()
-	}
-	wg.Wait()
-}
-
- -

-The variable i in the function literal is the same variable used by the loop, so -the read in the goroutine races with the loop increment. -(This program typically prints 55555, not 01234.) -The program can be fixed by making a copy of the variable: -

- -
-func main() {
-	var wg sync.WaitGroup
-	wg.Add(5)
-	for i := 0; i < 5; i++ {
-		go func(j int) {
-			fmt.Println(j) // Good. Read local copy of the loop counter.
-			wg.Done()
-		}(i)
-	}
-	wg.Wait()
-}
-
- -

Accidentally shared variable

- -
-// ParallelWrite writes data to file1 and file2, returns the errors.
-func ParallelWrite(data []byte) chan error {
-	res := make(chan error, 2)
-	f1, err := os.Create("file1")
-	if err != nil {
-		res <- err
-	} else {
-		go func() {
-			// This err is shared with the main goroutine,
-			// so the write races with the write below.
-			_, err = f1.Write(data)
-			res <- err
-			f1.Close()
-		}()
-	}
-	f2, err := os.Create("file2") // The second conflicting write to err.
-	if err != nil {
-		res <- err
-	} else {
-		go func() {
-			_, err = f2.Write(data)
-			res <- err
-			f2.Close()
-		}()
-	}
-	return res
-}
-
- -

-The fix is to introduce new variables in the goroutines (note the use of :=): -

- -
-			...
-			_, err := f1.Write(data)
-			...
-			_, err := f2.Write(data)
-			...
-
- -

Unprotected global variable

- -

-If the following code is called from several goroutines, it leads to races on the service map. -Concurrent reads and writes of the same map are not safe: -

- -
-var service map[string]net.Addr
-
-func RegisterService(name string, addr net.Addr) {
-	service[name] = addr
-}
-
-func LookupService(name string) net.Addr {
-	return service[name]
-}
-
- -

-To make the code safe, protect the accesses with a mutex: -

- -
-var (
-	service   map[string]net.Addr
-	serviceMu sync.Mutex
-)
-
-func RegisterService(name string, addr net.Addr) {
-	serviceMu.Lock()
-	defer serviceMu.Unlock()
-	service[name] = addr
-}
-
-func LookupService(name string) net.Addr {
-	serviceMu.Lock()
-	defer serviceMu.Unlock()
-	return service[name]
-}
-
- -

Primitive unprotected variable

- -

-Data races can happen on variables of primitive types as well (bool, int, int64, etc.), -as in this example: -

- -
-type Watchdog struct{ last int64 }
-
-func (w *Watchdog) KeepAlive() {
-	w.last = time.Now().UnixNano() // First conflicting access.
-}
-
-func (w *Watchdog) Start() {
-	go func() {
-		for {
-			time.Sleep(time.Second)
-			// Second conflicting access.
-			if w.last < time.Now().Add(-10*time.Second).UnixNano() {
-				fmt.Println("No keepalives for 10 seconds. Dying.")
-				os.Exit(1)
-			}
-		}
-	}()
-}
-
- -

-Even such "innocent" data races can lead to hard-to-debug problems caused by -non-atomicity of the memory accesses, -interference with compiler optimizations, -or reordering issues accessing processor memory . -

- -

-A typical fix for this race is to use a channel or a mutex. -To preserve the lock-free behavior, one can also use the -sync/atomic package. -

- -
-type Watchdog struct{ last int64 }
-
-func (w *Watchdog) KeepAlive() {
-	atomic.StoreInt64(&w.last, time.Now().UnixNano())
-}
-
-func (w *Watchdog) Start() {
-	go func() {
-		for {
-			time.Sleep(time.Second)
-			if atomic.LoadInt64(&w.last) < time.Now().Add(-10*time.Second).UnixNano() {
-				fmt.Println("No keepalives for 10 seconds. Dying.")
-				os.Exit(1)
-			}
-		}
-	}()
-}
-
- -

Unsynchronized send and close operations

- -

-As this example demonstrates, unsynchronized send and close operations -on the same channel can also be a race condition: -

- -
-c := make(chan struct{}) // or buffered channel
-
-// The race detector cannot derive the happens before relation
-// for the following send and close operations. These two operations
-// are unsynchronized and happen concurrently.
-go func() { c <- struct{}{} }()
-close(c)
-
- -

-According to the Go memory model, a send on a channel happens before -the corresponding receive from that channel completes. To synchronize -send and close operations, use a receive operation that guarantees -the send is done before the close: -

- -
-c := make(chan struct{}) // or buffered channel
-
-go func() { c <- struct{}{} }()
-<-c
-close(c)
-
- -

Supported Systems

- -

- The race detector runs on - linux/amd64, linux/ppc64le, - linux/arm64, freebsd/amd64, - netbsd/amd64, darwin/amd64, - darwin/arm64, and windows/amd64. -

- -

Runtime Overhead

- -

-The cost of race detection varies by program, but for a typical program, memory -usage may increase by 5-10x and execution time by 2-20x. -

- -

-The race detector currently allocates an extra 8 bytes per defer -and recover statement. Those extra allocations are not recovered until the goroutine -exits. This means that if you have a long-running goroutine that is -periodically issuing defer and recover calls, -the program memory usage may grow without bound. These memory allocations -will not show up in the output of runtime.ReadMemStats or -runtime/pprof. -

diff --git a/doc/articles/wiki/edit.html b/doc/articles/wiki/edit.html deleted file mode 100644 index 044c3bedea..0000000000 --- a/doc/articles/wiki/edit.html +++ /dev/null @@ -1,6 +0,0 @@ -

Editing {{.Title}}

- -
-
-
-
diff --git a/doc/articles/wiki/final-noclosure.go b/doc/articles/wiki/final-noclosure.go deleted file mode 100644 index d894e7d319..0000000000 --- a/doc/articles/wiki/final-noclosure.go +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -package main - -import ( - "errors" - "html/template" - "io/ioutil" - "log" - "net/http" - "regexp" -) - -type Page struct { - Title string - Body []byte -} - -func (p *Page) save() error { - filename := p.Title + ".txt" - return ioutil.WriteFile(filename, p.Body, 0600) -} - -func loadPage(title string) (*Page, error) { - filename := title + ".txt" - body, err := ioutil.ReadFile(filename) - if err != nil { - return nil, err - } - return &Page{Title: title, Body: body}, nil -} - -func viewHandler(w http.ResponseWriter, r *http.Request) { - title, err := getTitle(w, r) - if err != nil { - return - } - p, err := loadPage(title) - if err != nil { - http.Redirect(w, r, "/edit/"+title, http.StatusFound) - return - } - renderTemplate(w, "view", p) -} - -func editHandler(w http.ResponseWriter, r *http.Request) { - title, err := getTitle(w, r) - if err != nil { - return - } - p, err := loadPage(title) - if err != nil { - p = &Page{Title: title} - } - renderTemplate(w, "edit", p) -} - -func saveHandler(w http.ResponseWriter, r *http.Request) { - title, err := getTitle(w, r) - if err != nil { - return - } - body := r.FormValue("body") - p := &Page{Title: title, Body: []byte(body)} - err = p.save() - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - http.Redirect(w, r, "/view/"+title, http.StatusFound) -} - -func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) { - t, err := template.ParseFiles(tmpl + ".html") - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - err = t.Execute(w, p) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } -} - -var validPath = regexp.MustCompile("^/(edit|save|view)/([a-zA-Z0-9]+)$") - -func getTitle(w http.ResponseWriter, r *http.Request) (string, error) { - m := validPath.FindStringSubmatch(r.URL.Path) - if m == nil { - http.NotFound(w, r) - return "", errors.New("invalid Page Title") - } - return m[2], nil // The title is the second subexpression. -} - -func main() { - http.HandleFunc("/view/", viewHandler) - http.HandleFunc("/edit/", editHandler) - http.HandleFunc("/save/", saveHandler) - log.Fatal(http.ListenAndServe(":8080", nil)) -} diff --git a/doc/articles/wiki/final-noerror.go b/doc/articles/wiki/final-noerror.go deleted file mode 100644 index 250236d42e..0000000000 --- a/doc/articles/wiki/final-noerror.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -package main - -import ( - "html/template" - "io/ioutil" - "log" - "net/http" -) - -type Page struct { - Title string - Body []byte -} - -func (p *Page) save() error { - filename := p.Title + ".txt" - return ioutil.WriteFile(filename, p.Body, 0600) -} - -func loadPage(title string) (*Page, error) { - filename := title + ".txt" - body, err := ioutil.ReadFile(filename) - if err != nil { - return nil, err - } - return &Page{Title: title, Body: body}, nil -} - -func editHandler(w http.ResponseWriter, r *http.Request) { - title := r.URL.Path[len("/edit/"):] - p, err := loadPage(title) - if err != nil { - p = &Page{Title: title} - } - t, _ := template.ParseFiles("edit.html") - t.Execute(w, p) -} - -func viewHandler(w http.ResponseWriter, r *http.Request) { - title := r.URL.Path[len("/view/"):] - p, _ := loadPage(title) - t, _ := template.ParseFiles("view.html") - t.Execute(w, p) -} - -func main() { - http.HandleFunc("/view/", viewHandler) - http.HandleFunc("/edit/", editHandler) - log.Fatal(http.ListenAndServe(":8080", nil)) -} diff --git a/doc/articles/wiki/final-parsetemplate.go b/doc/articles/wiki/final-parsetemplate.go deleted file mode 100644 index 0b90cbd3bc..0000000000 --- a/doc/articles/wiki/final-parsetemplate.go +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -package main - -import ( - "html/template" - "io/ioutil" - "log" - "net/http" - "regexp" -) - -type Page struct { - Title string - Body []byte -} - -func (p *Page) save() error { - filename := p.Title + ".txt" - return ioutil.WriteFile(filename, p.Body, 0600) -} - -func loadPage(title string) (*Page, error) { - filename := title + ".txt" - body, err := ioutil.ReadFile(filename) - if err != nil { - return nil, err - } - return &Page{Title: title, Body: body}, nil -} - -func viewHandler(w http.ResponseWriter, r *http.Request, title string) { - p, err := loadPage(title) - if err != nil { - http.Redirect(w, r, "/edit/"+title, http.StatusFound) - return - } - renderTemplate(w, "view", p) -} - -func editHandler(w http.ResponseWriter, r *http.Request, title string) { - p, err := loadPage(title) - if err != nil { - p = &Page{Title: title} - } - renderTemplate(w, "edit", p) -} - -func saveHandler(w http.ResponseWriter, r *http.Request, title string) { - body := r.FormValue("body") - p := &Page{Title: title, Body: []byte(body)} - err := p.save() - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - http.Redirect(w, r, "/view/"+title, http.StatusFound) -} - -func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) { - t, err := template.ParseFiles(tmpl + ".html") - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - err = t.Execute(w, p) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } -} - -var validPath = regexp.MustCompile("^/(edit|save|view)/([a-zA-Z0-9]+)$") - -func makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - m := validPath.FindStringSubmatch(r.URL.Path) - if m == nil { - http.NotFound(w, r) - return - } - fn(w, r, m[2]) - } -} - -func main() { - http.HandleFunc("/view/", makeHandler(viewHandler)) - http.HandleFunc("/edit/", makeHandler(editHandler)) - http.HandleFunc("/save/", makeHandler(saveHandler)) - log.Fatal(http.ListenAndServe(":8080", nil)) -} diff --git a/doc/articles/wiki/final-template.go b/doc/articles/wiki/final-template.go deleted file mode 100644 index 5028664fe8..0000000000 --- a/doc/articles/wiki/final-template.go +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -package main - -import ( - "html/template" - "io/ioutil" - "log" - "net/http" -) - -type Page struct { - Title string - Body []byte -} - -func (p *Page) save() error { - filename := p.Title + ".txt" - return ioutil.WriteFile(filename, p.Body, 0600) -} - -func loadPage(title string) (*Page, error) { - filename := title + ".txt" - body, err := ioutil.ReadFile(filename) - if err != nil { - return nil, err - } - return &Page{Title: title, Body: body}, nil -} - -func editHandler(w http.ResponseWriter, r *http.Request) { - title := r.URL.Path[len("/edit/"):] - p, err := loadPage(title) - if err != nil { - p = &Page{Title: title} - } - renderTemplate(w, "edit", p) -} - -func viewHandler(w http.ResponseWriter, r *http.Request) { - title := r.URL.Path[len("/view/"):] - p, _ := loadPage(title) - renderTemplate(w, "view", p) -} - -func saveHandler(w http.ResponseWriter, r *http.Request) { - title := r.URL.Path[len("/save/"):] - body := r.FormValue("body") - p := &Page{Title: title, Body: []byte(body)} - p.save() - http.Redirect(w, r, "/view/"+title, http.StatusFound) -} - -func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) { - t, _ := template.ParseFiles(tmpl + ".html") - t.Execute(w, p) -} - -func main() { - http.HandleFunc("/view/", viewHandler) - http.HandleFunc("/edit/", editHandler) - http.HandleFunc("/save/", saveHandler) - log.Fatal(http.ListenAndServe(":8080", nil)) -} diff --git a/doc/articles/wiki/final.go b/doc/articles/wiki/final.go deleted file mode 100644 index b1439b08a9..0000000000 --- a/doc/articles/wiki/final.go +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -package main - -import ( - "html/template" - "io/ioutil" - "log" - "net/http" - "regexp" -) - -type Page struct { - Title string - Body []byte -} - -func (p *Page) save() error { - filename := p.Title + ".txt" - return ioutil.WriteFile(filename, p.Body, 0600) -} - -func loadPage(title string) (*Page, error) { - filename := title + ".txt" - body, err := ioutil.ReadFile(filename) - if err != nil { - return nil, err - } - return &Page{Title: title, Body: body}, nil -} - -func viewHandler(w http.ResponseWriter, r *http.Request, title string) { - p, err := loadPage(title) - if err != nil { - http.Redirect(w, r, "/edit/"+title, http.StatusFound) - return - } - renderTemplate(w, "view", p) -} - -func editHandler(w http.ResponseWriter, r *http.Request, title string) { - p, err := loadPage(title) - if err != nil { - p = &Page{Title: title} - } - renderTemplate(w, "edit", p) -} - -func saveHandler(w http.ResponseWriter, r *http.Request, title string) { - body := r.FormValue("body") - p := &Page{Title: title, Body: []byte(body)} - err := p.save() - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - http.Redirect(w, r, "/view/"+title, http.StatusFound) -} - -var templates = template.Must(template.ParseFiles("edit.html", "view.html")) - -func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) { - err := templates.ExecuteTemplate(w, tmpl+".html", p) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } -} - -var validPath = regexp.MustCompile("^/(edit|save|view)/([a-zA-Z0-9]+)$") - -func makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - m := validPath.FindStringSubmatch(r.URL.Path) - if m == nil { - http.NotFound(w, r) - return - } - fn(w, r, m[2]) - } -} - -func main() { - http.HandleFunc("/view/", makeHandler(viewHandler)) - http.HandleFunc("/edit/", makeHandler(editHandler)) - http.HandleFunc("/save/", makeHandler(saveHandler)) - - log.Fatal(http.ListenAndServe(":8080", nil)) -} diff --git a/doc/articles/wiki/final_test.go b/doc/articles/wiki/final_test.go deleted file mode 100644 index 764469976e..0000000000 --- a/doc/articles/wiki/final_test.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -package main - -import ( - "fmt" - "log" - "net" - "net/http" -) - -func serve() error { - l, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - log.Fatal(err) - } - fmt.Println(l.Addr().String()) - s := &http.Server{} - return s.Serve(l) -} diff --git a/doc/articles/wiki/go.mod b/doc/articles/wiki/go.mod deleted file mode 100644 index 38153ed79f..0000000000 --- a/doc/articles/wiki/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module doc/articles/wiki - -go 1.14 diff --git a/doc/articles/wiki/http-sample.go b/doc/articles/wiki/http-sample.go deleted file mode 100644 index 803b88c4eb..0000000000 --- a/doc/articles/wiki/http-sample.go +++ /dev/null @@ -1,18 +0,0 @@ -// +build ignore - -package main - -import ( - "fmt" - "log" - "net/http" -) - -func handler(w http.ResponseWriter, r *http.Request) { - fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:]) -} - -func main() { - http.HandleFunc("/", handler) - log.Fatal(http.ListenAndServe(":8080", nil)) -} diff --git a/doc/articles/wiki/index.html b/doc/articles/wiki/index.html deleted file mode 100644 index a74a58e317..0000000000 --- a/doc/articles/wiki/index.html +++ /dev/null @@ -1,741 +0,0 @@ - - -

Introduction

- -

-Covered in this tutorial: -

-
    -
  • Creating a data structure with load and save methods
  • -
  • Using the net/http package to build web applications -
  • Using the html/template package to process HTML templates
  • -
  • Using the regexp package to validate user input
  • -
  • Using closures
  • -
- -

-Assumed knowledge: -

-
    -
  • Programming experience
  • -
  • Understanding of basic web technologies (HTTP, HTML)
  • -
  • Some UNIX/DOS command-line knowledge
  • -
- -

Getting Started

- -

-At present, you need to have a FreeBSD, Linux, OS X, or Windows machine to run Go. -We will use $ to represent the command prompt. -

- -

-Install Go (see the Installation Instructions). -

- -

-Make a new directory for this tutorial inside your GOPATH and cd to it: -

- -
-$ mkdir gowiki
-$ cd gowiki
-
- -

-Create a file named wiki.go, open it in your favorite editor, and -add the following lines: -

- -
-package main
-
-import (
-	"fmt"
-	"io/ioutil"
-)
-
- -

-We import the fmt and ioutil packages from the Go -standard library. Later, as we implement additional functionality, we will -add more packages to this import declaration. -

- -

Data Structures

- -

-Let's start by defining the data structures. A wiki consists of a series of -interconnected pages, each of which has a title and a body (the page content). -Here, we define Page as a struct with two fields representing -the title and body. -

- -{{code "doc/articles/wiki/part1.go" `/^type Page/` `/}/`}} - -

-The type []byte means "a byte slice". -(See Slices: usage and -internals for more on slices.) -The Body element is a []byte rather than -string because that is the type expected by the io -libraries we will use, as you'll see below. -

- -

-The Page struct describes how page data will be stored in memory. -But what about persistent storage? We can address that by creating a -save method on Page: -

- -{{code "doc/articles/wiki/part1.go" `/^func.*Page.*save/` `/}/`}} - -

-This method's signature reads: "This is a method named save that -takes as its receiver p, a pointer to Page . It takes -no parameters, and returns a value of type error." -

- -

-This method will save the Page's Body to a text -file. For simplicity, we will use the Title as the file name. -

- -

-The save method returns an error value because -that is the return type of WriteFile (a standard library function -that writes a byte slice to a file). The save method returns the -error value, to let the application handle it should anything go wrong while -writing the file. If all goes well, Page.save() will return -nil (the zero-value for pointers, interfaces, and some other -types). -

- -

-The octal integer literal 0600, passed as the third parameter to -WriteFile, indicates that the file should be created with -read-write permissions for the current user only. (See the Unix man page -open(2) for details.) -

- -

-In addition to saving pages, we will want to load pages, too: -

- -{{code "doc/articles/wiki/part1-noerror.go" `/^func loadPage/` `/^}/`}} - -

-The function loadPage constructs the file name from the title -parameter, reads the file's contents into a new variable body, and -returns a pointer to a Page literal constructed with the proper -title and body values. -

- -

-Functions can return multiple values. The standard library function -io.ReadFile returns []byte and error. -In loadPage, error isn't being handled yet; the "blank identifier" -represented by the underscore (_) symbol is used to throw away the -error return value (in essence, assigning the value to nothing). -

- -

-But what happens if ReadFile encounters an error? For example, -the file might not exist. We should not ignore such errors. Let's modify the -function to return *Page and error. -

- -{{code "doc/articles/wiki/part1.go" `/^func loadPage/` `/^}/`}} - -

-Callers of this function can now check the second parameter; if it is -nil then it has successfully loaded a Page. If not, it will be an -error that can be handled by the caller (see the -language specification for details). -

- -

-At this point we have a simple data structure and the ability to save to and -load from a file. Let's write a main function to test what we've -written: -

- -{{code "doc/articles/wiki/part1.go" `/^func main/` `/^}/`}} - -

-After compiling and executing this code, a file named TestPage.txt -would be created, containing the contents of p1. The file would -then be read into the struct p2, and its Body element -printed to the screen. -

- -

-You can compile and run the program like this: -

- -
-$ go build wiki.go
-$ ./wiki
-This is a sample Page.
-
- -

-(If you're using Windows you must type "wiki" without the -"./" to run the program.) -

- -

-Click here to view the code we've written so far. -

- -

Introducing the net/http package (an interlude)

- -

-Here's a full working example of a simple web server: -

- -{{code "doc/articles/wiki/http-sample.go"}} - -

-The main function begins with a call to -http.HandleFunc, which tells the http package to -handle all requests to the web root ("/") with -handler. -

- -

-It then calls http.ListenAndServe, specifying that it should -listen on port 8080 on any interface (":8080"). (Don't -worry about its second parameter, nil, for now.) -This function will block until the program is terminated. -

- -

-ListenAndServe always returns an error, since it only returns when an -unexpected error occurs. -In order to log that error we wrap the function call with log.Fatal. -

- -

-The function handler is of the type http.HandlerFunc. -It takes an http.ResponseWriter and an http.Request as -its arguments. -

- -

-An http.ResponseWriter value assembles the HTTP server's response; by writing -to it, we send data to the HTTP client. -

- -

-An http.Request is a data structure that represents the client -HTTP request. r.URL.Path is the path component -of the request URL. The trailing [1:] means -"create a sub-slice of Path from the 1st character to the end." -This drops the leading "/" from the path name. -

- -

-If you run this program and access the URL: -

-
http://localhost:8080/monkeys
-

-the program would present a page containing: -

-
Hi there, I love monkeys!
- -

Using net/http to serve wiki pages

- -

-To use the net/http package, it must be imported: -

- -
-import (
-	"fmt"
-	"io/ioutil"
-	"log"
-	"net/http"
-)
-
- -

-Let's create a handler, viewHandler that will allow users to -view a wiki page. It will handle URLs prefixed with "/view/". -

- -{{code "doc/articles/wiki/part2.go" `/^func viewHandler/` `/^}/`}} - -

-Again, note the use of _ to ignore the error -return value from loadPage. This is done here for simplicity -and generally considered bad practice. We will attend to this later. -

- -

-First, this function extracts the page title from r.URL.Path, -the path component of the request URL. -The Path is re-sliced with [len("/view/"):] to drop -the leading "/view/" component of the request path. -This is because the path will invariably begin with "/view/", -which is not part of the page's title. -

- -

-The function then loads the page data, formats the page with a string of simple -HTML, and writes it to w, the http.ResponseWriter. -

- -

-To use this handler, we rewrite our main function to -initialize http using the viewHandler to handle -any requests under the path /view/. -

- -{{code "doc/articles/wiki/part2.go" `/^func main/` `/^}/`}} - -

-Click here to view the code we've written so far. -

- -

-Let's create some page data (as test.txt), compile our code, and -try serving a wiki page. -

- -

-Open test.txt file in your editor, and save the string "Hello world" (without quotes) -in it. -

- -
-$ go build wiki.go
-$ ./wiki
-
- -

-(If you're using Windows you must type "wiki" without the -"./" to run the program.) -

- -

-With this web server running, a visit to http://localhost:8080/view/test -should show a page titled "test" containing the words "Hello world". -

- -

Editing Pages

- -

-A wiki is not a wiki without the ability to edit pages. Let's create two new -handlers: one named editHandler to display an 'edit page' form, -and the other named saveHandler to save the data entered via the -form. -

- -

-First, we add them to main(): -

- -{{code "doc/articles/wiki/final-noclosure.go" `/^func main/` `/^}/`}} - -

-The function editHandler loads the page -(or, if it doesn't exist, create an empty Page struct), -and displays an HTML form. -

- -{{code "doc/articles/wiki/notemplate.go" `/^func editHandler/` `/^}/`}} - -

-This function will work fine, but all that hard-coded HTML is ugly. -Of course, there is a better way. -

- -

The html/template package

- -

-The html/template package is part of the Go standard library. -We can use html/template to keep the HTML in a separate file, -allowing us to change the layout of our edit page without modifying the -underlying Go code. -

- -

-First, we must add html/template to the list of imports. We -also won't be using fmt anymore, so we have to remove that. -

- -
-import (
-	"html/template"
-	"io/ioutil"
-	"net/http"
-)
-
- -

-Let's create a template file containing the HTML form. -Open a new file named edit.html, and add the following lines: -

- -{{code "doc/articles/wiki/edit.html"}} - -

-Modify editHandler to use the template, instead of the hard-coded -HTML: -

- -{{code "doc/articles/wiki/final-noerror.go" `/^func editHandler/` `/^}/`}} - -

-The function template.ParseFiles will read the contents of -edit.html and return a *template.Template. -

- -

-The method t.Execute executes the template, writing the -generated HTML to the http.ResponseWriter. -The .Title and .Body dotted identifiers refer to -p.Title and p.Body. -

- -

-Template directives are enclosed in double curly braces. -The printf "%s" .Body instruction is a function call -that outputs .Body as a string instead of a stream of bytes, -the same as a call to fmt.Printf. -The html/template package helps guarantee that only safe and -correct-looking HTML is generated by template actions. For instance, it -automatically escapes any greater than sign (>), replacing it -with &gt;, to make sure user data does not corrupt the form -HTML. -

- -

-Since we're working with templates now, let's create a template for our -viewHandler called view.html: -

- -{{code "doc/articles/wiki/view.html"}} - -

-Modify viewHandler accordingly: -

- -{{code "doc/articles/wiki/final-noerror.go" `/^func viewHandler/` `/^}/`}} - -

-Notice that we've used almost exactly the same templating code in both -handlers. Let's remove this duplication by moving the templating code -to its own function: -

- -{{code "doc/articles/wiki/final-template.go" `/^func renderTemplate/` `/^}/`}} - -

-And modify the handlers to use that function: -

- -{{code "doc/articles/wiki/final-template.go" `/^func viewHandler/` `/^}/`}} -{{code "doc/articles/wiki/final-template.go" `/^func editHandler/` `/^}/`}} - -

-If we comment out the registration of our unimplemented save handler in -main, we can once again build and test our program. -Click here to view the code we've written so far. -

- -

Handling non-existent pages

- -

-What if you visit -/view/APageThatDoesntExist? You'll see a page containing -HTML. This is because it ignores the error return value from -loadPage and continues to try and fill out the template -with no data. Instead, if the requested Page doesn't exist, it should -redirect the client to the edit Page so the content may be created: -

- -{{code "doc/articles/wiki/part3-errorhandling.go" `/^func viewHandler/` `/^}/`}} - -

-The http.Redirect function adds an HTTP status code of -http.StatusFound (302) and a Location -header to the HTTP response. -

- -

Saving Pages

- -

-The function saveHandler will handle the submission of forms -located on the edit pages. After uncommenting the related line in -main, let's implement the handler: -

- -{{code "doc/articles/wiki/final-template.go" `/^func saveHandler/` `/^}/`}} - -

-The page title (provided in the URL) and the form's only field, -Body, are stored in a new Page. -The save() method is then called to write the data to a file, -and the client is redirected to the /view/ page. -

- -

-The value returned by FormValue is of type string. -We must convert that value to []byte before it will fit into -the Page struct. We use []byte(body) to perform -the conversion. -

- -

Error handling

- -

-There are several places in our program where errors are being ignored. This -is bad practice, not least because when an error does occur the program will -have unintended behavior. A better solution is to handle the errors and return -an error message to the user. That way if something does go wrong, the server -will function exactly how we want and the user can be notified. -

- -

-First, let's handle the errors in renderTemplate: -

- -{{code "doc/articles/wiki/final-parsetemplate.go" `/^func renderTemplate/` `/^}/`}} - -

-The http.Error function sends a specified HTTP response code -(in this case "Internal Server Error") and error message. -Already the decision to put this in a separate function is paying off. -

- -

-Now let's fix up saveHandler: -

- -{{code "doc/articles/wiki/part3-errorhandling.go" `/^func saveHandler/` `/^}/`}} - -

-Any errors that occur during p.save() will be reported -to the user. -

- -

Template caching

- -

-There is an inefficiency in this code: renderTemplate calls -ParseFiles every time a page is rendered. -A better approach would be to call ParseFiles once at program -initialization, parsing all templates into a single *Template. -Then we can use the -ExecuteTemplate -method to render a specific template. -

- -

-First we create a global variable named templates, and initialize -it with ParseFiles. -

- -{{code "doc/articles/wiki/final.go" `/var templates/`}} - -

-The function template.Must is a convenience wrapper that panics -when passed a non-nil error value, and otherwise returns the -*Template unaltered. A panic is appropriate here; if the templates -can't be loaded the only sensible thing to do is exit the program. -

- -

-The ParseFiles function takes any number of string arguments that -identify our template files, and parses those files into templates that are -named after the base file name. If we were to add more templates to our -program, we would add their names to the ParseFiles call's -arguments. -

- -

-We then modify the renderTemplate function to call the -templates.ExecuteTemplate method with the name of the appropriate -template: -

- -{{code "doc/articles/wiki/final.go" `/func renderTemplate/` `/^}/`}} - -

-Note that the template name is the template file name, so we must -append ".html" to the tmpl argument. -

- -

Validation

- -

-As you may have observed, this program has a serious security flaw: a user -can supply an arbitrary path to be read/written on the server. To mitigate -this, we can write a function to validate the title with a regular expression. -

- -

-First, add "regexp" to the import list. -Then we can create a global variable to store our validation -expression: -

- -{{code "doc/articles/wiki/final-noclosure.go" `/^var validPath/`}} - -

-The function regexp.MustCompile will parse and compile the -regular expression, and return a regexp.Regexp. -MustCompile is distinct from Compile in that it will -panic if the expression compilation fails, while Compile returns -an error as a second parameter. -

- -

-Now, let's write a function that uses the validPath -expression to validate path and extract the page title: -

- -{{code "doc/articles/wiki/final-noclosure.go" `/func getTitle/` `/^}/`}} - -

-If the title is valid, it will be returned along with a nil -error value. If the title is invalid, the function will write a -"404 Not Found" error to the HTTP connection, and return an error to the -handler. To create a new error, we have to import the errors -package. -

- -

-Let's put a call to getTitle in each of the handlers: -

- -{{code "doc/articles/wiki/final-noclosure.go" `/^func viewHandler/` `/^}/`}} -{{code "doc/articles/wiki/final-noclosure.go" `/^func editHandler/` `/^}/`}} -{{code "doc/articles/wiki/final-noclosure.go" `/^func saveHandler/` `/^}/`}} - -

Introducing Function Literals and Closures

- -

-Catching the error condition in each handler introduces a lot of repeated code. -What if we could wrap each of the handlers in a function that does this -validation and error checking? Go's -function -literals provide a powerful means of abstracting functionality -that can help us here. -

- -

-First, we re-write the function definition of each of the handlers to accept -a title string: -

- -
-func viewHandler(w http.ResponseWriter, r *http.Request, title string)
-func editHandler(w http.ResponseWriter, r *http.Request, title string)
-func saveHandler(w http.ResponseWriter, r *http.Request, title string)
-
- -

-Now let's define a wrapper function that takes a function of the above -type, and returns a function of type http.HandlerFunc -(suitable to be passed to the function http.HandleFunc): -

- -
-func makeHandler(fn func (http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
-	return func(w http.ResponseWriter, r *http.Request) {
-		// Here we will extract the page title from the Request,
-		// and call the provided handler 'fn'
-	}
-}
-
- -

-The returned function is called a closure because it encloses values defined -outside of it. In this case, the variable fn (the single argument -to makeHandler) is enclosed by the closure. The variable -fn will be one of our save, edit, or view handlers. -

- -

-Now we can take the code from getTitle and use it here -(with some minor modifications): -

- -{{code "doc/articles/wiki/final.go" `/func makeHandler/` `/^}/`}} - -

-The closure returned by makeHandler is a function that takes -an http.ResponseWriter and http.Request (in other -words, an http.HandlerFunc). -The closure extracts the title from the request path, and -validates it with the validPath regexp. If the -title is invalid, an error will be written to the -ResponseWriter using the http.NotFound function. -If the title is valid, the enclosed handler function -fn will be called with the ResponseWriter, -Request, and title as arguments. -

- -

-Now we can wrap the handler functions with makeHandler in -main, before they are registered with the http -package: -

- -{{code "doc/articles/wiki/final.go" `/func main/` `/^}/`}} - -

-Finally we remove the calls to getTitle from the handler functions, -making them much simpler: -

- -{{code "doc/articles/wiki/final.go" `/^func viewHandler/` `/^}/`}} -{{code "doc/articles/wiki/final.go" `/^func editHandler/` `/^}/`}} -{{code "doc/articles/wiki/final.go" `/^func saveHandler/` `/^}/`}} - -

Try it out!

- -

-Click here to view the final code listing. -

- -

-Recompile the code, and run the app: -

- -
-$ go build wiki.go
-$ ./wiki
-
- -

-Visiting http://localhost:8080/view/ANewPage -should present you with the page edit form. You should then be able to -enter some text, click 'Save', and be redirected to the newly created page. -

- -

Other tasks

- -

-Here are some simple tasks you might want to tackle on your own: -

- -
    -
  • Store templates in tmpl/ and page data in data/. -
  • Add a handler to make the web root redirect to - /view/FrontPage.
  • -
  • Spruce up the page templates by making them valid HTML and adding some - CSS rules.
  • -
  • Implement inter-page linking by converting instances of - [PageName] to
    - <a href="/view/PageName">PageName</a>. - (hint: you could use regexp.ReplaceAllFunc to do this) -
  • -
diff --git a/doc/articles/wiki/notemplate.go b/doc/articles/wiki/notemplate.go deleted file mode 100644 index 4b358f298a..0000000000 --- a/doc/articles/wiki/notemplate.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -package main - -import ( - "fmt" - "io/ioutil" - "log" - "net/http" -) - -type Page struct { - Title string - Body []byte -} - -func (p *Page) save() error { - filename := p.Title + ".txt" - return ioutil.WriteFile(filename, p.Body, 0600) -} - -func loadPage(title string) (*Page, error) { - filename := title + ".txt" - body, err := ioutil.ReadFile(filename) - if err != nil { - return nil, err - } - return &Page{Title: title, Body: body}, nil -} - -func viewHandler(w http.ResponseWriter, r *http.Request) { - title := r.URL.Path[len("/view/"):] - p, _ := loadPage(title) - fmt.Fprintf(w, "

%s

%s
", p.Title, p.Body) -} - -func editHandler(w http.ResponseWriter, r *http.Request) { - title := r.URL.Path[len("/edit/"):] - p, err := loadPage(title) - if err != nil { - p = &Page{Title: title} - } - fmt.Fprintf(w, "

Editing %s

"+ - "
"+ - "
"+ - ""+ - "
", - p.Title, p.Title, p.Body) -} - -func main() { - http.HandleFunc("/view/", viewHandler) - http.HandleFunc("/edit/", editHandler) - log.Fatal(http.ListenAndServe(":8080", nil)) -} diff --git a/doc/articles/wiki/part1-noerror.go b/doc/articles/wiki/part1-noerror.go deleted file mode 100644 index 913c6dce2e..0000000000 --- a/doc/articles/wiki/part1-noerror.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -package main - -import ( - "fmt" - "io/ioutil" -) - -type Page struct { - Title string - Body []byte -} - -func (p *Page) save() error { - filename := p.Title + ".txt" - return ioutil.WriteFile(filename, p.Body, 0600) -} - -func loadPage(title string) *Page { - filename := title + ".txt" - body, _ := ioutil.ReadFile(filename) - return &Page{Title: title, Body: body} -} - -func main() { - p1 := &Page{Title: "TestPage", Body: []byte("This is a sample page.")} - p1.save() - p2 := loadPage("TestPage") - fmt.Println(string(p2.Body)) -} diff --git a/doc/articles/wiki/part1.go b/doc/articles/wiki/part1.go deleted file mode 100644 index 2ff1abd281..0000000000 --- a/doc/articles/wiki/part1.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -package main - -import ( - "fmt" - "io/ioutil" -) - -type Page struct { - Title string - Body []byte -} - -func (p *Page) save() error { - filename := p.Title + ".txt" - return ioutil.WriteFile(filename, p.Body, 0600) -} - -func loadPage(title string) (*Page, error) { - filename := title + ".txt" - body, err := ioutil.ReadFile(filename) - if err != nil { - return nil, err - } - return &Page{Title: title, Body: body}, nil -} - -func main() { - p1 := &Page{Title: "TestPage", Body: []byte("This is a sample Page.")} - p1.save() - p2, _ := loadPage("TestPage") - fmt.Println(string(p2.Body)) -} diff --git a/doc/articles/wiki/part2.go b/doc/articles/wiki/part2.go deleted file mode 100644 index db92f4c710..0000000000 --- a/doc/articles/wiki/part2.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -package main - -import ( - "fmt" - "io/ioutil" - "log" - "net/http" -) - -type Page struct { - Title string - Body []byte -} - -func (p *Page) save() error { - filename := p.Title + ".txt" - return ioutil.WriteFile(filename, p.Body, 0600) -} - -func loadPage(title string) (*Page, error) { - filename := title + ".txt" - body, err := ioutil.ReadFile(filename) - if err != nil { - return nil, err - } - return &Page{Title: title, Body: body}, nil -} - -func viewHandler(w http.ResponseWriter, r *http.Request) { - title := r.URL.Path[len("/view/"):] - p, _ := loadPage(title) - fmt.Fprintf(w, "

%s

%s
", p.Title, p.Body) -} - -func main() { - http.HandleFunc("/view/", viewHandler) - log.Fatal(http.ListenAndServe(":8080", nil)) -} diff --git a/doc/articles/wiki/part3-errorhandling.go b/doc/articles/wiki/part3-errorhandling.go deleted file mode 100644 index 2c8b42d05a..0000000000 --- a/doc/articles/wiki/part3-errorhandling.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -package main - -import ( - "html/template" - "io/ioutil" - "log" - "net/http" -) - -type Page struct { - Title string - Body []byte -} - -func (p *Page) save() error { - filename := p.Title + ".txt" - return ioutil.WriteFile(filename, p.Body, 0600) -} - -func loadPage(title string) (*Page, error) { - filename := title + ".txt" - body, err := ioutil.ReadFile(filename) - if err != nil { - return nil, err - } - return &Page{Title: title, Body: body}, nil -} - -func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) { - t, _ := template.ParseFiles(tmpl + ".html") - t.Execute(w, p) -} - -func viewHandler(w http.ResponseWriter, r *http.Request) { - title := r.URL.Path[len("/view/"):] - p, err := loadPage(title) - if err != nil { - http.Redirect(w, r, "/edit/"+title, http.StatusFound) - return - } - renderTemplate(w, "view", p) -} - -func editHandler(w http.ResponseWriter, r *http.Request) { - title := r.URL.Path[len("/edit/"):] - p, err := loadPage(title) - if err != nil { - p = &Page{Title: title} - } - renderTemplate(w, "edit", p) -} - -func saveHandler(w http.ResponseWriter, r *http.Request) { - title := r.URL.Path[len("/save/"):] - body := r.FormValue("body") - p := &Page{Title: title, Body: []byte(body)} - err := p.save() - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - http.Redirect(w, r, "/view/"+title, http.StatusFound) -} - -func main() { - http.HandleFunc("/view/", viewHandler) - http.HandleFunc("/edit/", editHandler) - http.HandleFunc("/save/", saveHandler) - log.Fatal(http.ListenAndServe(":8080", nil)) -} diff --git a/doc/articles/wiki/part3.go b/doc/articles/wiki/part3.go deleted file mode 100644 index 437ea336cb..0000000000 --- a/doc/articles/wiki/part3.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -package main - -import ( - "html/template" - "io/ioutil" - "log" - "net/http" -) - -type Page struct { - Title string - Body []byte -} - -func (p *Page) save() error { - filename := p.Title + ".txt" - return ioutil.WriteFile(filename, p.Body, 0600) -} - -func loadPage(title string) (*Page, error) { - filename := title + ".txt" - body, err := ioutil.ReadFile(filename) - if err != nil { - return nil, err - } - return &Page{Title: title, Body: body}, nil -} - -func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) { - t, _ := template.ParseFiles(tmpl + ".html") - t.Execute(w, p) -} - -func viewHandler(w http.ResponseWriter, r *http.Request) { - title := r.URL.Path[len("/view/"):] - p, _ := loadPage(title) - renderTemplate(w, "view", p) -} - -func editHandler(w http.ResponseWriter, r *http.Request) { - title := r.URL.Path[len("/edit/"):] - p, err := loadPage(title) - if err != nil { - p = &Page{Title: title} - } - renderTemplate(w, "edit", p) -} - -func main() { - http.HandleFunc("/view/", viewHandler) - http.HandleFunc("/edit/", editHandler) - //http.HandleFunc("/save/", saveHandler) - log.Fatal(http.ListenAndServe(":8080", nil)) -} diff --git a/doc/articles/wiki/test_Test.txt.good b/doc/articles/wiki/test_Test.txt.good deleted file mode 100644 index f0eec86f61..0000000000 --- a/doc/articles/wiki/test_Test.txt.good +++ /dev/null @@ -1 +0,0 @@ -some content \ No newline at end of file diff --git a/doc/articles/wiki/test_edit.good b/doc/articles/wiki/test_edit.good deleted file mode 100644 index 36c6dbb732..0000000000 --- a/doc/articles/wiki/test_edit.good +++ /dev/null @@ -1,6 +0,0 @@ -

Editing Test

- -
-
-
-
diff --git a/doc/articles/wiki/test_view.good b/doc/articles/wiki/test_view.good deleted file mode 100644 index 07e8edb22e..0000000000 --- a/doc/articles/wiki/test_view.good +++ /dev/null @@ -1,5 +0,0 @@ -

Test

- -

[edit]

- -
some content
diff --git a/doc/articles/wiki/view.html b/doc/articles/wiki/view.html deleted file mode 100644 index b1e87efe80..0000000000 --- a/doc/articles/wiki/view.html +++ /dev/null @@ -1,5 +0,0 @@ -

{{.Title}}

- -

[edit]

- -
{{printf "%s" .Body}}
diff --git a/doc/articles/wiki/wiki_test.go b/doc/articles/wiki/wiki_test.go deleted file mode 100644 index 1d976fd77e..0000000000 --- a/doc/articles/wiki/wiki_test.go +++ /dev/null @@ -1,165 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main_test - -import ( - "bytes" - "fmt" - "io/ioutil" - "net/http" - "os" - "os/exec" - "path/filepath" - "strings" - "testing" -) - -func TestSnippetsCompile(t *testing.T) { - if testing.Short() { - t.Skip("skipping slow builds in short mode") - } - - goFiles, err := filepath.Glob("*.go") - if err != nil { - t.Fatal(err) - } - - for _, f := range goFiles { - if strings.HasSuffix(f, "_test.go") { - continue - } - f := f - t.Run(f, func(t *testing.T) { - t.Parallel() - - cmd := exec.Command("go", "build", "-o", os.DevNull, f) - out, err := cmd.CombinedOutput() - if err != nil { - t.Errorf("%s: %v\n%s", strings.Join(cmd.Args, " "), err, out) - } - }) - } -} - -func TestWikiServer(t *testing.T) { - must := func(err error) { - if err != nil { - t.Helper() - t.Fatal(err) - } - } - - dir, err := ioutil.TempDir("", t.Name()) - must(err) - defer os.RemoveAll(dir) - - // We're testing a walkthrough example of how to write a server. - // - // That server hard-codes a port number to make the walkthrough simpler, but - // we can't assume that the hard-coded port is available on an arbitrary - // builder. So we'll patch out the hard-coded port, and replace it with a - // function that writes the server's address to stdout - // so that we can read it and know where to send the test requests. - - finalGo, err := ioutil.ReadFile("final.go") - must(err) - const patchOld = `log.Fatal(http.ListenAndServe(":8080", nil))` - patched := bytes.ReplaceAll(finalGo, []byte(patchOld), []byte(`log.Fatal(serve())`)) - if bytes.Equal(patched, finalGo) { - t.Fatalf("Can't patch final.go: %q not found.", patchOld) - } - must(ioutil.WriteFile(filepath.Join(dir, "final_patched.go"), patched, 0644)) - - // Build the server binary from the patched sources. - // The 'go' command requires that they all be in the same directory. - // final_test.go provides the implemtation for our serve function. - must(copyFile(filepath.Join(dir, "final_srv.go"), "final_test.go")) - cmd := exec.Command("go", "build", - "-o", filepath.Join(dir, "final.exe"), - filepath.Join(dir, "final_patched.go"), - filepath.Join(dir, "final_srv.go")) - out, err := cmd.CombinedOutput() - if err != nil { - t.Fatalf("%s: %v\n%s", strings.Join(cmd.Args, " "), err, out) - } - - // Run the server in our temporary directory so that it can - // write its content there. It also needs a couple of template files, - // and looks for them in the same directory. - must(copyFile(filepath.Join(dir, "edit.html"), "edit.html")) - must(copyFile(filepath.Join(dir, "view.html"), "view.html")) - cmd = exec.Command(filepath.Join(dir, "final.exe")) - cmd.Dir = dir - stderr := bytes.NewBuffer(nil) - cmd.Stderr = stderr - stdout, err := cmd.StdoutPipe() - must(err) - must(cmd.Start()) - - defer func() { - cmd.Process.Kill() - err := cmd.Wait() - if stderr.Len() > 0 { - t.Logf("%s: %v\n%s", strings.Join(cmd.Args, " "), err, stderr) - } - }() - - var addr string - if _, err := fmt.Fscanln(stdout, &addr); err != nil || addr == "" { - t.Fatalf("Failed to read server address: %v", err) - } - - // The server is up and has told us its address. - // Make sure that its HTTP API works as described in the article. - - r, err := http.Get(fmt.Sprintf("http://%s/edit/Test", addr)) - must(err) - responseMustMatchFile(t, r, "test_edit.good") - - r, err = http.Post(fmt.Sprintf("http://%s/save/Test", addr), - "application/x-www-form-urlencoded", - strings.NewReader("body=some%20content")) - must(err) - responseMustMatchFile(t, r, "test_view.good") - - gotTxt, err := ioutil.ReadFile(filepath.Join(dir, "Test.txt")) - must(err) - wantTxt, err := ioutil.ReadFile("test_Test.txt.good") - must(err) - if !bytes.Equal(wantTxt, gotTxt) { - t.Fatalf("Test.txt differs from expected after posting to /save.\ngot:\n%s\nwant:\n%s", gotTxt, wantTxt) - } - - r, err = http.Get(fmt.Sprintf("http://%s/view/Test", addr)) - must(err) - responseMustMatchFile(t, r, "test_view.good") -} - -func responseMustMatchFile(t *testing.T, r *http.Response, filename string) { - t.Helper() - - defer r.Body.Close() - body, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatal(err) - } - - wantBody, err := ioutil.ReadFile(filename) - if err != nil { - t.Fatal(err) - } - - if !bytes.Equal(body, wantBody) { - t.Fatalf("%v: body does not match %s.\ngot:\n%s\nwant:\n%s", r.Request.URL, filename, body, wantBody) - } -} - -func copyFile(dst, src string) error { - buf, err := ioutil.ReadFile(src) - if err != nil { - return err - } - return ioutil.WriteFile(dst, buf, 0644) -} diff --git a/doc/cmd.html b/doc/cmd.html deleted file mode 100644 index c3bd918144..0000000000 --- a/doc/cmd.html +++ /dev/null @@ -1,100 +0,0 @@ - - -

-There is a suite of programs to build and process Go source code. -Instead of being run directly, programs in the suite are usually invoked -by the go program. -

- -

-The most common way to run these programs is as a subcommand of the go program, -for instance as go fmt. Run like this, the command operates on -complete packages of Go source code, with the go program invoking the -underlying binary with arguments appropriate to package-level processing. -

- -

-The programs can also be run as stand-alone binaries, with unmodified arguments, -using the go tool subcommand, such as go tool cgo. -For most commands this is mainly useful for debugging. -Some of the commands, such as pprof, are accessible only through -the go tool subcommand. -

- -

-Finally the fmt and godoc commands are installed -as regular binaries called gofmt and godoc because -they are so often referenced. -

- -

-Click on the links for more documentation, invocation methods, and usage details. -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Name    Synopsis
go     -The go program manages Go source code and runs the other -commands listed here. -See the command docs for usage -details. -
cgo    Cgo enables the creation of Go packages that call C code.
cover    Cover is a program for creating and analyzing the coverage profiles -generated by "go test -coverprofile".
fix    Fix finds Go programs that use old features of the language and libraries -and rewrites them to use newer ones.
fmt    Fmt formats Go packages, it is also available as an independent -gofmt command with more general options.
godoc    Godoc extracts and generates documentation for Go packages.
vet    Vet examines Go source code and reports suspicious constructs, such as Printf -calls whose arguments do not align with the format string.
- -

-This is an abridged list. See the full command reference -for documentation of the compilers and more. -

diff --git a/doc/codewalk/codewalk.css b/doc/codewalk/codewalk.css deleted file mode 100644 index a0814e4d2d..0000000000 --- a/doc/codewalk/codewalk.css +++ /dev/null @@ -1,234 +0,0 @@ -/* - Copyright 2010 The Go Authors. All rights reserved. - Use of this source code is governed by a BSD-style - license that can be found in the LICENSE file. -*/ - -#codewalk-main { - text-align: left; - width: 100%; - overflow: auto; -} - -#code-display { - border: 0; - width: 100%; -} - -.setting { - font-size: 8pt; - color: #888888; - padding: 5px; -} - -.hotkey { - text-decoration: underline; -} - -/* Style for Comments (the left-hand column) */ - -#comment-column { - margin: 0pt; - width: 30%; -} - -#comment-column.right { - float: right; -} - -#comment-column.left { - float: left; -} - -#comment-area { - overflow-x: hidden; - overflow-y: auto; -} - -.comment { - cursor: pointer; - font-size: 16px; - border: 2px solid #ba9836; - margin-bottom: 10px; - margin-right: 10px; /* yes, for both .left and .right */ -} - -.comment:last-child { - margin-bottom: 0px; -} - -.right .comment { - margin-left: 10px; -} - -.right .comment.first { -} - -.right .comment.last { -} - -.left .comment.first { -} - -.left .comment.last { -} - -.comment.selected { - border-color: #99b2cb; -} - -.right .comment.selected { - border-left-width: 12px; - margin-left: 0px; -} - -.left .comment.selected { - border-right-width: 12px; - margin-right: 0px; -} - -.comment-link { - display: none; -} - -.comment-title { - font-size: small; - font-weight: bold; - background-color: #fffff0; - padding-right: 10px; - padding-left: 10px; - padding-top: 5px; - padding-bottom: 5px; -} - -.right .comment-title { -} - -.left .comment-title { -} - -.comment.selected .comment-title { - background-color: #f8f8ff; -} - -.comment-text { - overflow: auto; - padding-left: 10px; - padding-right: 10px; - padding-top: 10px; - padding-bottom: 5px; - font-size: small; - line-height: 1.3em; -} - -.comment-text p { - margin-top: 0em; - margin-bottom: 0.5em; -} - -.comment-text p:last-child { - margin-bottom: 0em; -} - -.file-name { - font-size: x-small; - padding-top: 0px; - padding-bottom: 5px; -} - -.hidden-filepaths .file-name { - display: none; -} - -.path-dir { - color: #555; -} - -.path-file { - color: #555; -} - - -/* Style for Code (the right-hand column) */ - -/* Wrapper for the code column to make widths get calculated correctly */ -#code-column { - display: block; - position: relative; - margin: 0pt; - width: 70%; -} - -#code-column.left { - float: left; -} - -#code-column.right { - float: right; -} - -#code-area { - background-color: #f8f8ff; - border: 2px solid #99b2cb; - padding: 5px; -} - -.left #code-area { - margin-right: -1px; -} - -.right #code-area { - margin-left: -1px; -} - -#code-header { - margin-bottom: 5px; -} - -#code { - background-color: white; -} - -code { - font-size: 100%; -} - -.codewalkhighlight { - font-weight: bold; - background-color: #f8f8ff; -} - -#code-display { - margin-top: 0px; - margin-bottom: 0px; -} - -#sizer { - position: absolute; - cursor: col-resize; - left: 0px; - top: 0px; - width: 8px; -} - -/* Style for options (bottom strip) */ - -#code-options { - display: none; -} - -#code-options > span { - padding-right: 20px; -} - -#code-options .selected { - border-bottom: 1px dotted; -} - -#comment-options { - text-align: center; -} - -div#content { - padding-bottom: 0em; -} diff --git a/doc/codewalk/codewalk.js b/doc/codewalk/codewalk.js deleted file mode 100644 index 4f59a8fc89..0000000000 --- a/doc/codewalk/codewalk.js +++ /dev/null @@ -1,305 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -/** - * A class to hold information about the Codewalk Viewer. - * @param {jQuery} context The top element in whose context the viewer should - * operate. It will not touch any elements above this one. - * @constructor - */ - var CodewalkViewer = function(context) { - this.context = context; - - /** - * The div that contains all of the comments and their controls. - */ - this.commentColumn = this.context.find('#comment-column'); - - /** - * The div that contains the comments proper. - */ - this.commentArea = this.context.find('#comment-area'); - - /** - * The div that wraps the iframe with the code, as well as the drop down menu - * listing the different files. - * @type {jQuery} - */ - this.codeColumn = this.context.find('#code-column'); - - /** - * The div that contains the code but excludes the options strip. - * @type {jQuery} - */ - this.codeArea = this.context.find('#code-area'); - - /** - * The iframe that holds the code (from Sourcerer). - * @type {jQuery} - */ - this.codeDisplay = this.context.find('#code-display'); - - /** - * The overlaid div used as a grab handle for sizing the code/comment panes. - * @type {jQuery} - */ - this.sizer = this.context.find('#sizer'); - - /** - * The full-screen overlay that ensures we don't lose track of the mouse - * while dragging. - * @type {jQuery} - */ - this.overlay = this.context.find('#overlay'); - - /** - * The hidden input field that we use to hold the focus so that we can detect - * shortcut keypresses. - * @type {jQuery} - */ - this.shortcutInput = this.context.find('#shortcut-input'); - - /** - * The last comment that was selected. - * @type {jQuery} - */ - this.lastSelected = null; -}; - -/** - * Minimum width of the comments or code pane, in pixels. - * @type {number} - */ -CodewalkViewer.MIN_PANE_WIDTH = 200; - -/** - * Navigate the code iframe to the given url and update the code popout link. - * @param {string} url The target URL. - * @param {Object} opt_window Window dependency injection for testing only. - */ -CodewalkViewer.prototype.navigateToCode = function(url, opt_window) { - if (!opt_window) opt_window = window; - // Each iframe is represented by two distinct objects in the DOM: an iframe - // object and a window object. These do not expose the same capabilities. - // Here we need to get the window representation to get the location member, - // so we access it directly through window[] since jQuery returns the iframe - // representation. - // We replace location rather than set so as not to create a history for code - // navigation. - opt_window['code-display'].location.replace(url); - var k = url.indexOf('&'); - if (k != -1) url = url.slice(0, k); - k = url.indexOf('fileprint='); - if (k != -1) url = url.slice(k+10, url.length); - this.context.find('#code-popout-link').attr('href', url); -}; - -/** - * Selects the first comment from the list and forces a refresh of the code - * view. - */ -CodewalkViewer.prototype.selectFirstComment = function() { - // TODO(rsc): handle case where there are no comments - var firstSourcererLink = this.context.find('.comment:first'); - this.changeSelectedComment(firstSourcererLink); -}; - -/** - * Sets the target on all links nested inside comments to be _blank. - */ -CodewalkViewer.prototype.targetCommentLinksAtBlank = function() { - this.context.find('.comment a[href], #description a[href]').each(function() { - if (!this.target) this.target = '_blank'; - }); -}; - -/** - * Installs event handlers for all the events we care about. - */ -CodewalkViewer.prototype.installEventHandlers = function() { - var self = this; - - this.context.find('.comment') - .click(function(event) { - if (jQuery(event.target).is('a[href]')) return true; - self.changeSelectedComment(jQuery(this)); - return false; - }); - - this.context.find('#code-selector') - .change(function() {self.navigateToCode(jQuery(this).val());}); - - this.context.find('#description-table .quote-feet.setting') - .click(function() {self.toggleDescription(jQuery(this)); return false;}); - - this.sizer - .mousedown(function(ev) {self.startSizerDrag(ev); return false;}); - this.overlay - .mouseup(function(ev) {self.endSizerDrag(ev); return false;}) - .mousemove(function(ev) {self.handleSizerDrag(ev); return false;}); - - this.context.find('#prev-comment') - .click(function() { - self.changeSelectedComment(self.lastSelected.prev()); return false; - }); - - this.context.find('#next-comment') - .click(function() { - self.changeSelectedComment(self.lastSelected.next()); return false; - }); - - // Workaround for Firefox 2 and 3, which steal focus from the main document - // whenever the iframe content is (re)loaded. The input field is not shown, - // but is a way for us to bring focus back to a place where we can detect - // keypresses. - this.context.find('#code-display') - .load(function(ev) {self.shortcutInput.focus();}); - - jQuery(document).keypress(function(ev) { - switch(ev.which) { - case 110: // 'n' - self.changeSelectedComment(self.lastSelected.next()); - return false; - case 112: // 'p' - self.changeSelectedComment(self.lastSelected.prev()); - return false; - default: // ignore - } - }); - - window.onresize = function() {self.updateHeight();}; -}; - -/** - * Starts dragging the pane sizer. - * @param {Object} ev The mousedown event that started us dragging. - */ -CodewalkViewer.prototype.startSizerDrag = function(ev) { - this.initialCodeWidth = this.codeColumn.width(); - this.initialCommentsWidth = this.commentColumn.width(); - this.initialMouseX = ev.pageX; - this.overlay.show(); -}; - -/** - * Handles dragging the pane sizer. - * @param {Object} ev The mousemove event updating dragging position. - */ -CodewalkViewer.prototype.handleSizerDrag = function(ev) { - var delta = ev.pageX - this.initialMouseX; - if (this.codeColumn.is('.right')) delta = -delta; - var proposedCodeWidth = this.initialCodeWidth + delta; - var proposedCommentWidth = this.initialCommentsWidth - delta; - var mw = CodewalkViewer.MIN_PANE_WIDTH; - if (proposedCodeWidth < mw) delta = mw - this.initialCodeWidth; - if (proposedCommentWidth < mw) delta = this.initialCommentsWidth - mw; - proposedCodeWidth = this.initialCodeWidth + delta; - proposedCommentWidth = this.initialCommentsWidth - delta; - // If window is too small, don't even try to resize. - if (proposedCodeWidth < mw || proposedCommentWidth < mw) return; - this.codeColumn.width(proposedCodeWidth); - this.commentColumn.width(proposedCommentWidth); - this.options.codeWidth = parseInt( - this.codeColumn.width() / - (this.codeColumn.width() + this.commentColumn.width()) * 100); - this.context.find('#code-column-width').text(this.options.codeWidth + '%'); -}; - -/** - * Ends dragging the pane sizer. - * @param {Object} ev The mouseup event that caused us to stop dragging. - */ -CodewalkViewer.prototype.endSizerDrag = function(ev) { - this.overlay.hide(); - this.updateHeight(); -}; - -/** - * Toggles the Codewalk description between being shown and hidden. - * @param {jQuery} target The target that was clicked to trigger this function. - */ -CodewalkViewer.prototype.toggleDescription = function(target) { - var description = this.context.find('#description'); - description.toggle(); - target.find('span').text(description.is(':hidden') ? 'show' : 'hide'); - this.updateHeight(); -}; - -/** - * Changes the side of the window on which the code is shown and saves the - * setting in a cookie. - * @param {string?} codeSide The side on which the code should be, either - * 'left' or 'right'. - */ -CodewalkViewer.prototype.changeCodeSide = function(codeSide) { - var commentSide = codeSide == 'left' ? 'right' : 'left'; - this.context.find('#set-code-' + codeSide).addClass('selected'); - this.context.find('#set-code-' + commentSide).removeClass('selected'); - // Remove previous side class and add new one. - this.codeColumn.addClass(codeSide).removeClass(commentSide); - this.commentColumn.addClass(commentSide).removeClass(codeSide); - this.sizer.css(codeSide, 'auto').css(commentSide, 0); - this.options.codeSide = codeSide; -}; - -/** - * Adds selected class to newly selected comment, removes selected style from - * previously selected comment, changes drop down options so that the correct - * file is selected, and updates the code popout link. - * @param {jQuery} target The target that was clicked to trigger this function. - */ -CodewalkViewer.prototype.changeSelectedComment = function(target) { - var currentFile = target.find('.comment-link').attr('href'); - if (!currentFile) return; - - if (!(this.lastSelected && this.lastSelected.get(0) === target.get(0))) { - if (this.lastSelected) this.lastSelected.removeClass('selected'); - target.addClass('selected'); - this.lastSelected = target; - var targetTop = target.position().top; - var parentTop = target.parent().position().top; - if (targetTop + target.height() > parentTop + target.parent().height() || - targetTop < parentTop) { - var delta = targetTop - parentTop; - target.parent().animate( - {'scrollTop': target.parent().scrollTop() + delta}, - Math.max(delta / 2, 200), 'swing'); - } - var fname = currentFile.match(/(?:select=|fileprint=)\/[^&]+/)[0]; - fname = fname.slice(fname.indexOf('=')+2, fname.length); - this.context.find('#code-selector').val(fname); - this.context.find('#prev-comment').toggleClass( - 'disabled', !target.prev().length); - this.context.find('#next-comment').toggleClass( - 'disabled', !target.next().length); - } - - // Force original file even if user hasn't changed comments since they may - // have navigated away from it within the iframe without us knowing. - this.navigateToCode(currentFile); -}; - -/** - * Updates the viewer by changing the height of the comments and code so that - * they fit within the height of the window. The function is typically called - * after the user changes the window size. - */ -CodewalkViewer.prototype.updateHeight = function() { - var windowHeight = jQuery(window).height() - 5 // GOK - var areaHeight = windowHeight - this.codeArea.offset().top - var footerHeight = this.context.find('#footer').outerHeight(true) - this.commentArea.height(areaHeight - footerHeight - this.context.find('#comment-options').outerHeight(true)) - var codeHeight = areaHeight - footerHeight - 15 // GOK - this.codeArea.height(codeHeight) - this.codeDisplay.height(codeHeight - this.codeDisplay.offset().top + this.codeArea.offset().top); - this.sizer.height(codeHeight); -}; - -window.initFuncs.push(function() { - var viewer = new CodewalkViewer(jQuery('#codewalk-main')); - viewer.selectFirstComment(); - viewer.targetCommentLinksAtBlank(); - viewer.installEventHandlers(); - viewer.updateHeight(); -}); diff --git a/doc/codewalk/codewalk.xml b/doc/codewalk/codewalk.xml deleted file mode 100644 index 34e6e91938..0000000000 --- a/doc/codewalk/codewalk.xml +++ /dev/null @@ -1,124 +0,0 @@ - - - - A codewalk is a guided tour through a piece of code. - It consists of a sequence of steps, each typically explaining - a highlighted section of code. -

- - The godoc web server translates - an XML file like the one in the main window pane into the HTML - page that you're viewing now. -

- - The codewalk with URL path /doc/codewalk/name - is loaded from the input file $GOROOT/doc/codewalk/name.xml. -

- - This codewalk explains how to write a codewalk by examining - its own source code, - $GOROOT/doc/codewalk/codewalk.xml, - shown in the main window pane to the left. -
- - - The codewalk input file is an XML file containing a single - <codewalk> element. - That element's title attribute gives the title - that is used both on the codewalk page and in the codewalk list. - - - - Each step in the codewalk is a <step> element - nested inside the main <codewalk>. - The step element's title attribute gives the step's title, - which is shown in a shaded bar above the main step text. - The element's src attribute specifies the source - code to show in the main window pane and, optionally, a range of - lines to highlight. -

- - The first step in this codewalk does not highlight any lines: - its src is just a file name. -
- - - The most complex part of the codewalk specification is - saying what lines to highlight. - Instead of ordinary line numbers, - the codewalk uses an address syntax that makes it possible - to describe the match by its content. - As the file gets edited, this descriptive address has a better - chance to continue to refer to the right section of the file. -

- - To specify a source line, use a src attribute of the form - filename:address, - where address is an address in the syntax used by the text editors sam and acme. -

- - The simplest address is a single regular expression. - The highlighted line in the main window pane shows that the - address for the “Title” step was /title=/, - which matches the first instance of that regular expression (title=) in the file. -
- - - To highlight a range of source lines, the simplest address to use is - a pair of regular expressions - /regexp1/,/regexp2/. - The highlight begins with the line containing the first match for regexp1 - and ends with the line containing the first match for regexp2 - after the end of the match for regexp1. - Ignoring the HTML quoting, - The line containing the first match for regexp1 will be the first one highlighted, - and the line containing the first match for regexp2. -

- - The address /<step/,/step>/ looks for the first instance of - <step in the file, and then starting after that point, - looks for the first instance of step>. - (Click on the “Steps” step above to see the highlight in action.) - Note that the < and > had to be written - using XML escapes in order to be valid XML. -
- - - The /regexp/ - and /regexp1/,/regexp2/ - forms suffice for most highlighting. -

- - The full address syntax is summarized in this table - (an excerpt of Table II from - The text editor sam): -

- - - - - - - - - - - - - - - - - - - - -
Simple addresses
#nThe empty string after character n
nLine n
/regexp/The first following match of the regular expression
$The null string at the end of the file
Compound addresses
a1+a2The address a2 evaluated starting at the right of a1
a1-a2The address a2 evaluated in the reverse direction starting at the left of a1
a1,a2From the left of a1 to the right of a2 (default 0,$).
-
- - - -
diff --git a/doc/codewalk/codewalk_test.go b/doc/codewalk/codewalk_test.go deleted file mode 100644 index 31f078ac26..0000000000 --- a/doc/codewalk/codewalk_test.go +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2019 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main_test - -import ( - "bytes" - "os" - "os/exec" - "strings" - "testing" -) - -// TestMarkov tests the code dependency of markov.xml. -func TestMarkov(t *testing.T) { - cmd := exec.Command("go", "run", "markov.go") - cmd.Stdin = strings.NewReader("foo") - cmd.Stderr = bytes.NewBuffer(nil) - out, err := cmd.Output() - if err != nil { - t.Fatalf("%s: %v\n%s", strings.Join(cmd.Args, " "), err, cmd.Stderr) - } - - if !bytes.Equal(out, []byte("foo\n")) { - t.Fatalf(`%s with input "foo" did not output "foo":\n%s`, strings.Join(cmd.Args, " "), out) - } -} - -// TestPig tests the code dependency of functions.xml. -func TestPig(t *testing.T) { - cmd := exec.Command("go", "run", "pig.go") - cmd.Stderr = bytes.NewBuffer(nil) - out, err := cmd.Output() - if err != nil { - t.Fatalf("%s: %v\n%s", strings.Join(cmd.Args, " "), err, cmd.Stderr) - } - - const want = "Wins, losses staying at k = 100: 210/990 (21.2%), 780/990 (78.8%)\n" - if !bytes.Contains(out, []byte(want)) { - t.Fatalf(`%s: unexpected output\ngot:\n%s\nwant output containing:\n%s`, strings.Join(cmd.Args, " "), out, want) - } -} - -// TestURLPoll tests the code dependency of sharemem.xml. -func TestURLPoll(t *testing.T) { - cmd := exec.Command("go", "build", "-o", os.DevNull, "urlpoll.go") - out, err := cmd.CombinedOutput() - if err != nil { - t.Fatalf("%s: %v\n%s", strings.Join(cmd.Args, " "), err, out) - } -} diff --git a/doc/codewalk/functions.xml b/doc/codewalk/functions.xml deleted file mode 100644 index db518dcc06..0000000000 --- a/doc/codewalk/functions.xml +++ /dev/null @@ -1,105 +0,0 @@ - - - - Go supports first class functions, higher-order functions, user-defined - function types, function literals, closures, and multiple return values. -

- - This rich feature set supports a functional programming style in a strongly - typed language. -

- - In this codewalk we will look at a simple program that simulates a dice game - called Pig and evaluates - basic strategies. -
- - - Pig is a two-player game played with a 6-sided die. Each turn, you may roll or stay. -
    -
  • If you roll a 1, you lose all points for your turn and play passes to - your opponent. Any other roll adds its value to your turn score.
  • -
  • If you stay, your turn score is added to your total score, and play passes - to your opponent.
  • -
- - The first person to reach 100 total points wins. -

- - The score type stores the scores of the current and opposing - players, in addition to the points accumulated during the current turn. -
- - - In Go, functions can be passed around just like any other value. A function's - type signature describes the types of its arguments and return values. -

- - The action type is a function that takes a score - and returns the resulting score and whether the current turn is - over. -

- - If the turn is over, the player and opponent fields - in the resulting score should be swapped, as it is now the other player's - turn. -
- - - Go functions can return multiple values. -

- - The functions roll and stay each return a pair of - values. They also match the action type signature. These - action functions define the rules of Pig. -
- - - A function can use other functions as arguments and return values. -

- - A strategy is a function that takes a score as input - and returns an action to perform.
- (Remember, an action is itself a function.) -
- - - Anonymous functions can be declared in Go, as in this example. Function - literals are closures: they inherit the scope of the function in which they - are declared. -

- - One basic strategy in Pig is to continue rolling until you have accumulated at - least k points in a turn, and then stay. The argument k is - enclosed by this function literal, which matches the strategy type - signature. -
- - - We simulate a game of Pig by calling an action to update the - score until one player reaches 100 points. Each - action is selected by calling the strategy function - associated with the current player. - - - - The roundRobin function simulates a tournament and tallies wins. - Each strategy plays each other strategy gamesPerSeries times. - - - - Variadic functions like ratioString take a variable number of - arguments. These arguments are available as a slice inside the function. - - - - The main function defines 100 basic strategies, simulates a round - robin tournament, and then prints the win/loss record of each strategy. -

- - Among these strategies, staying at 25 is best, but the optimal strategy for - Pig is much more complex. -
- -
diff --git a/doc/codewalk/markov.go b/doc/codewalk/markov.go deleted file mode 100644 index 5f62e05144..0000000000 --- a/doc/codewalk/markov.go +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -/* -Generating random text: a Markov chain algorithm - -Based on the program presented in the "Design and Implementation" chapter -of The Practice of Programming (Kernighan and Pike, Addison-Wesley 1999). -See also Computer Recreations, Scientific American 260, 122 - 125 (1989). - -A Markov chain algorithm generates text by creating a statistical model of -potential textual suffixes for a given prefix. Consider this text: - - I am not a number! I am a free man! - -Our Markov chain algorithm would arrange this text into this set of prefixes -and suffixes, or "chain": (This table assumes a prefix length of two words.) - - Prefix Suffix - - "" "" I - "" I am - I am a - I am not - a free man! - am a free - am not a - a number! I - number! I am - not a number! - -To generate text using this table we select an initial prefix ("I am", for -example), choose one of the suffixes associated with that prefix at random -with probability determined by the input statistics ("a"), -and then create a new prefix by removing the first word from the prefix -and appending the suffix (making the new prefix is "am a"). Repeat this process -until we can't find any suffixes for the current prefix or we exceed the word -limit. (The word limit is necessary as the chain table may contain cycles.) - -Our version of this program reads text from standard input, parsing it into a -Markov chain, and writes generated text to standard output. -The prefix and output lengths can be specified using the -prefix and -words -flags on the command-line. -*/ -package main - -import ( - "bufio" - "flag" - "fmt" - "io" - "math/rand" - "os" - "strings" - "time" -) - -// Prefix is a Markov chain prefix of one or more words. -type Prefix []string - -// String returns the Prefix as a string (for use as a map key). -func (p Prefix) String() string { - return strings.Join(p, " ") -} - -// Shift removes the first word from the Prefix and appends the given word. -func (p Prefix) Shift(word string) { - copy(p, p[1:]) - p[len(p)-1] = word -} - -// Chain contains a map ("chain") of prefixes to a list of suffixes. -// A prefix is a string of prefixLen words joined with spaces. -// A suffix is a single word. A prefix can have multiple suffixes. -type Chain struct { - chain map[string][]string - prefixLen int -} - -// NewChain returns a new Chain with prefixes of prefixLen words. -func NewChain(prefixLen int) *Chain { - return &Chain{make(map[string][]string), prefixLen} -} - -// Build reads text from the provided Reader and -// parses it into prefixes and suffixes that are stored in Chain. -func (c *Chain) Build(r io.Reader) { - br := bufio.NewReader(r) - p := make(Prefix, c.prefixLen) - for { - var s string - if _, err := fmt.Fscan(br, &s); err != nil { - break - } - key := p.String() - c.chain[key] = append(c.chain[key], s) - p.Shift(s) - } -} - -// Generate returns a string of at most n words generated from Chain. -func (c *Chain) Generate(n int) string { - p := make(Prefix, c.prefixLen) - var words []string - for i := 0; i < n; i++ { - choices := c.chain[p.String()] - if len(choices) == 0 { - break - } - next := choices[rand.Intn(len(choices))] - words = append(words, next) - p.Shift(next) - } - return strings.Join(words, " ") -} - -func main() { - // Register command-line flags. - numWords := flag.Int("words", 100, "maximum number of words to print") - prefixLen := flag.Int("prefix", 2, "prefix length in words") - - flag.Parse() // Parse command-line flags. - rand.Seed(time.Now().UnixNano()) // Seed the random number generator. - - c := NewChain(*prefixLen) // Initialize a new Chain. - c.Build(os.Stdin) // Build chains from standard input. - text := c.Generate(*numWords) // Generate text. - fmt.Println(text) // Write text to standard output. -} diff --git a/doc/codewalk/markov.xml b/doc/codewalk/markov.xml deleted file mode 100644 index 7e44840dc4..0000000000 --- a/doc/codewalk/markov.xml +++ /dev/null @@ -1,307 +0,0 @@ - - - - - - This codewalk describes a program that generates random text using - a Markov chain algorithm. The package comment describes the algorithm - and the operation of the program. Please read it before continuing. - - - - A chain consists of a prefix and a suffix. Each prefix is a set - number of words, while a suffix is a single word. - A prefix can have an arbitrary number of suffixes. - To model this data, we use a map[string][]string. - Each map key is a prefix (a string) and its values are - lists of suffixes (a slice of strings, []string). -

- Here is the example table from the package comment - as modeled by this data structure: -
-map[string][]string{
-	" ":          {"I"},
-	" I":         {"am"},
-	"I am":       {"a", "not"},
-	"a free":     {"man!"},
-	"am a":       {"free"},
-	"am not":     {"a"},
-	"a number!":  {"I"},
-	"number! I":  {"am"},
-	"not a":      {"number!"},
-}
- While each prefix consists of multiple words, we - store prefixes in the map as a single string. - It would seem more natural to store the prefix as a - []string, but we can't do this with a map because the - key type of a map must implement equality (and slices do not). -

- Therefore, in most of our code we will model prefixes as a - []string and join the strings together with a space - to generate the map key: -
-Prefix               Map key
-
-[]string{"", ""}     " "
-[]string{"", "I"}    " I"
-[]string{"I", "am"}  "I am"
-
-
- - - The complete state of the chain table consists of the table itself and - the word length of the prefixes. The Chain struct stores - this data. - - - - The Chain struct has two unexported fields (those that - do not begin with an upper case character), and so we write a - NewChain constructor function that initializes the - chain map with make and sets the - prefixLen field. -

- This is constructor function is not strictly necessary as this entire - program is within a single package (main) and therefore - there is little practical difference between exported and unexported - fields. We could just as easily write out the contents of this function - when we want to construct a new Chain. - But using these unexported fields is good practice; it clearly denotes - that only methods of Chain and its constructor function should access - those fields. Also, structuring Chain like this means we - could easily move it into its own package at some later date. -
- - - Since we'll be working with prefixes often, we define a - Prefix type with the concrete type []string. - Defining a named type clearly allows us to be explicit when we are - working with a prefix instead of just a []string. - Also, in Go we can define methods on any named type (not just structs), - so we can add methods that operate on Prefix if we need to. - - - - The first method we define on Prefix is - String. It returns a string representation - of a Prefix by joining the slice elements together with - spaces. We will use this method to generate keys when working with - the chain map. - - - - The Build method reads text from an io.Reader - and parses it into prefixes and suffixes that are stored in the - Chain. -

- The io.Reader is an - interface type that is widely used by the standard library and - other Go code. Our code uses the - fmt.Fscan function, which - reads space-separated values from an io.Reader. -

- The Build method returns once the Reader's - Read method returns io.EOF (end of file) - or some other read error occurs. -
- - - This function does many small reads, which can be inefficient for some - Readers. For efficiency we wrap the provided - io.Reader with - bufio.NewReader to create a - new io.Reader that provides buffering. - - - - At the top of the function we make a Prefix slice - p using the Chain's prefixLen - field as its length. - We'll use this variable to hold the current prefix and mutate it with - each new word we encounter. - - - - In our loop we read words from the Reader into a - string variable s using - fmt.Fscan. Since Fscan uses space to - separate each input value, each call will yield just one word - (including punctuation), which is exactly what we need. -

- Fscan returns an error if it encounters a read error - (io.EOF, for example) or if it can't scan the requested - value (in our case, a single string). In either case we just want to - stop scanning, so we break out of the loop. -
- - - The word stored in s is a new suffix. We add the new - prefix/suffix combination to the chain map by computing - the map key with p.String and appending the suffix - to the slice stored under that key. -

- The built-in append function appends elements to a slice - and allocates new storage when necessary. When the provided slice is - nil, append allocates a new slice. - This behavior conveniently ties in with the semantics of our map: - retrieving an unset key returns the zero value of the value type and - the zero value of []string is nil. - When our program encounters a new prefix (yielding a nil - value in the map) append will allocate a new slice. -

- For more information about the append function and slices - in general see the - Slices: usage and internals article. -
- - - Before reading the next word our algorithm requires us to drop the - first word from the prefix and push the current suffix onto the prefix. -

- When in this state -
-p == Prefix{"I", "am"}
-s == "not" 
- the new value for p would be -
-p == Prefix{"am", "not"}
- This operation is also required during text generation so we put - the code to perform this mutation of the slice inside a method on - Prefix named Shift. -
- - - The Shift method uses the built-in copy - function to copy the last len(p)-1 elements of p to - the start of the slice, effectively moving the elements - one index to the left (if you consider zero as the leftmost index). -
-p := Prefix{"I", "am"}
-copy(p, p[1:])
-// p == Prefix{"am", "am"}
- We then assign the provided word to the last index - of the slice: -
-// suffix == "not"
-p[len(p)-1] = suffix
-// p == Prefix{"am", "not"}
-
- - - The Generate method is similar to Build - except that instead of reading words from a Reader - and storing them in a map, it reads words from the map and - appends them to a slice (words). -

- Generate uses a conditional for loop to generate - up to n words. -
- - - At each iteration of the loop we retrieve a list of potential suffixes - for the current prefix. We access the chain map at key - p.String() and assign its contents to choices. -

- If len(choices) is zero we break out of the loop as there - are no potential suffixes for that prefix. - This test also works if the key isn't present in the map at all: - in that case, choices will be nil and the - length of a nil slice is zero. -
- - - To choose a suffix we use the - rand.Intn function. - It returns a random integer up to (but not including) the provided - value. Passing in len(choices) gives us a random index - into the full length of the list. -

- We use that index to pick our new suffix, assign it to - next and append it to the words slice. -

- Next, we Shift the new suffix onto the prefix just as - we did in the Build method. -
- - - Before returning the generated text as a string, we use the - strings.Join function to join the elements of - the words slice together, separated by spaces. - - - - To make it easy to tweak the prefix and generated text lengths we - use the flag package to parse - command-line flags. -

- These calls to flag.Int register new flags with the - flag package. The arguments to Int are the - flag name, its default value, and a description. The Int - function returns a pointer to an integer that will contain the - user-supplied value (or the default value if the flag was omitted on - the command-line). -
- - - The main function begins by parsing the command-line - flags with flag.Parse and seeding the rand - package's random number generator with the current time. -

- If the command-line flags provided by the user are invalid the - flag.Parse function will print an informative usage - message and terminate the program. -
- - - To create the new Chain we call NewChain - with the value of the prefix flag. -

- To build the chain we call Build with - os.Stdin (which implements io.Reader) so - that it will read its input from standard input. -
- - - Finally, to generate text we call Generate with - the value of the words flag and assigning the result - to the variable text. -

- Then we call fmt.Println to write the text to standard - output, followed by a carriage return. -
- - - To use this program, first build it with the - go command: -
-$ go build markov.go
- And then execute it while piping in some input text: -
-$ echo "a man a plan a canal panama" \
-	| ./markov -prefix=1
-a plan a man a plan a canal panama
- Here's a transcript of generating some text using the Go distribution's - README file as source material: -
-$ ./markov -words=10 < $GOROOT/README
-This is the source code repository for the Go source
-$ ./markov -prefix=1 -words=10 < $GOROOT/README
-This is the go directory (the one containing this README).
-$ ./markov -prefix=1 -words=10 < $GOROOT/README
-This is the variable if you have just untarred a
-
- - - The Generate function does a lot of allocations when it - builds the words slice. As an exercise, modify it to - take an io.Writer to which it incrementally writes the - generated text with Fprint. - Aside from being more efficient this makes Generate - more symmetrical to Build. - - -
diff --git a/doc/codewalk/pig.go b/doc/codewalk/pig.go deleted file mode 100644 index 941daaed16..0000000000 --- a/doc/codewalk/pig.go +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import ( - "fmt" - "math/rand" -) - -const ( - win = 100 // The winning score in a game of Pig - gamesPerSeries = 10 // The number of games per series to simulate -) - -// A score includes scores accumulated in previous turns for each player, -// as well as the points scored by the current player in this turn. -type score struct { - player, opponent, thisTurn int -} - -// An action transitions stochastically to a resulting score. -type action func(current score) (result score, turnIsOver bool) - -// roll returns the (result, turnIsOver) outcome of simulating a die roll. -// If the roll value is 1, then thisTurn score is abandoned, and the players' -// roles swap. Otherwise, the roll value is added to thisTurn. -func roll(s score) (score, bool) { - outcome := rand.Intn(6) + 1 // A random int in [1, 6] - if outcome == 1 { - return score{s.opponent, s.player, 0}, true - } - return score{s.player, s.opponent, outcome + s.thisTurn}, false -} - -// stay returns the (result, turnIsOver) outcome of staying. -// thisTurn score is added to the player's score, and the players' roles swap. -func stay(s score) (score, bool) { - return score{s.opponent, s.player + s.thisTurn, 0}, true -} - -// A strategy chooses an action for any given score. -type strategy func(score) action - -// stayAtK returns a strategy that rolls until thisTurn is at least k, then stays. -func stayAtK(k int) strategy { - return func(s score) action { - if s.thisTurn >= k { - return stay - } - return roll - } -} - -// play simulates a Pig game and returns the winner (0 or 1). -func play(strategy0, strategy1 strategy) int { - strategies := []strategy{strategy0, strategy1} - var s score - var turnIsOver bool - currentPlayer := rand.Intn(2) // Randomly decide who plays first - for s.player+s.thisTurn < win { - action := strategies[currentPlayer](s) - s, turnIsOver = action(s) - if turnIsOver { - currentPlayer = (currentPlayer + 1) % 2 - } - } - return currentPlayer -} - -// roundRobin simulates a series of games between every pair of strategies. -func roundRobin(strategies []strategy) ([]int, int) { - wins := make([]int, len(strategies)) - for i := 0; i < len(strategies); i++ { - for j := i + 1; j < len(strategies); j++ { - for k := 0; k < gamesPerSeries; k++ { - winner := play(strategies[i], strategies[j]) - if winner == 0 { - wins[i]++ - } else { - wins[j]++ - } - } - } - } - gamesPerStrategy := gamesPerSeries * (len(strategies) - 1) // no self play - return wins, gamesPerStrategy -} - -// ratioString takes a list of integer values and returns a string that lists -// each value and its percentage of the sum of all values. -// e.g., ratios(1, 2, 3) = "1/6 (16.7%), 2/6 (33.3%), 3/6 (50.0%)" -func ratioString(vals ...int) string { - total := 0 - for _, val := range vals { - total += val - } - s := "" - for _, val := range vals { - if s != "" { - s += ", " - } - pct := 100 * float64(val) / float64(total) - s += fmt.Sprintf("%d/%d (%0.1f%%)", val, total, pct) - } - return s -} - -func main() { - strategies := make([]strategy, win) - for k := range strategies { - strategies[k] = stayAtK(k + 1) - } - wins, games := roundRobin(strategies) - - for k := range strategies { - fmt.Printf("Wins, losses staying at k =% 4d: %s\n", - k+1, ratioString(wins[k], games-wins[k])) - } -} diff --git a/doc/codewalk/popout.png b/doc/codewalk/popout.png deleted file mode 100644 index 9c0c23638b..0000000000 Binary files a/doc/codewalk/popout.png and /dev/null differ diff --git a/doc/codewalk/sharemem.xml b/doc/codewalk/sharemem.xml deleted file mode 100644 index 8b47f12b7a..0000000000 --- a/doc/codewalk/sharemem.xml +++ /dev/null @@ -1,181 +0,0 @@ - - - -Go's approach to concurrency differs from the traditional use of -threads and shared memory. Philosophically, it can be summarized: -

-Don't communicate by sharing memory; share memory by communicating. -

-Channels allow you to pass references to data structures between goroutines. -If you consider this as passing around ownership of the data (the ability to -read and write it), they become a powerful and expressive synchronization -mechanism. -

-In this codewalk we will look at a simple program that polls a list of -URLs, checking their HTTP response codes and periodically printing their state. -
- - -The State type represents the state of a URL. -

-The Pollers send State values to the StateMonitor, -which maintains a map of the current state of each URL. -
- - -A Resource represents the state of a URL to be polled: the URL itself -and the number of errors encountered since the last successful poll. -

-When the program starts, it allocates one Resource for each URL. -The main goroutine and the Poller goroutines send the Resources to -each other on channels. -
- - -Each Poller receives Resource pointers from an input channel. -In this program, the convention is that sending a Resource pointer on -a channel passes ownership of the underlying data from the sender -to the receiver. Because of this convention, we know that -no two goroutines will access this Resource at the same time. -This means we don't have to worry about locking to prevent concurrent -access to these data structures. -

-The Poller processes the Resource by calling its Poll method. -

-It sends a State value to the status channel, to inform the StateMonitor -of the result of the Poll. -

-Finally, it sends the Resource pointer to the out channel. This can be -interpreted as the Poller saying "I'm done with this Resource" and -returning ownership of it to the main goroutine. -

-Several goroutines run Pollers, processing Resources in parallel. -
- - -The Poll method (of the Resource type) performs an HTTP HEAD request -for the Resource's URL and returns the HTTP response's status code. -If an error occurs, Poll logs the message to standard error and returns the -error string instead. - - - -The main function starts the Poller and StateMonitor goroutines -and then loops passing completed Resources back to the pending -channel after appropriate delays. - - - -First, main makes two channels of *Resource, pending and complete. -

-Inside main, a new goroutine sends one Resource per URL to pending -and the main goroutine receives completed Resources from complete. -

-The pending and complete channels are passed to each of the Poller -goroutines, within which they are known as in and out. -
- - -StateMonitor will initialize and launch a goroutine that stores the state -of each Resource. We will look at this function in detail later. -

-For now, the important thing to note is that it returns a channel of State, -which is saved as status and passed to the Poller goroutines. -
- - -Now that it has the necessary channels, main launches a number of -Poller goroutines, passing the channels as arguments. -The channels provide the means of communication between the main, Poller, and -StateMonitor goroutines. - - - -To add the initial work to the system, main starts a new goroutine -that allocates and sends one Resource per URL to pending. -

-The new goroutine is necessary because unbuffered channel sends and -receives are synchronous. That means these channel sends will block until -the Pollers are ready to read from pending. -

-Were these sends performed in the main goroutine with fewer Pollers than -channel sends, the program would reach a deadlock situation, because -main would not yet be receiving from complete. -

-Exercise for the reader: modify this part of the program to read a list of -URLs from a file. (You may want to move this goroutine into its own -named function.) -
- - -When a Poller is done with a Resource, it sends it on the complete channel. -This loop receives those Resource pointers from complete. -For each received Resource, it starts a new goroutine calling -the Resource's Sleep method. Using a new goroutine for each -ensures that the sleeps can happen in parallel. -

-Note that any single Resource pointer may only be sent on either pending or -complete at any one time. This ensures that a Resource is either being -handled by a Poller goroutine or sleeping, but never both simultaneously. -In this way, we share our Resource data by communicating. -
- - -Sleep calls time.Sleep to pause before sending the Resource to done. -The pause will either be of a fixed length (pollInterval) plus an -additional delay proportional to the number of sequential errors (r.errCount). -

-This is an example of a typical Go idiom: a function intended to run inside -a goroutine takes a channel, upon which it sends its return value -(or other indication of completed state). -
- - -The StateMonitor receives State values on a channel and periodically -outputs the state of all Resources being polled by the program. - - - -The variable updates is a channel of State, on which the Poller goroutines -send State values. -

-This channel is returned by the function. -
- - -The variable urlStatus is a map of URLs to their most recent status. - - - -A time.Ticker is an object that repeatedly sends a value on a channel at a -specified interval. -

-In this case, ticker triggers the printing of the current state to -standard output every updateInterval nanoseconds. -
- - -StateMonitor will loop forever, selecting on two channels: -ticker.C and update. The select statement blocks until one of its -communications is ready to proceed. -

-When StateMonitor receives a tick from ticker.C, it calls logState to -print the current state. When it receives a State update from updates, -it records the new status in the urlStatus map. -

-Notice that this goroutine owns the urlStatus data structure, -ensuring that it can only be accessed sequentially. -This prevents memory corruption issues that might arise from parallel reads -and/or writes to a shared map. -
- - -In this codewalk we have explored a simple example of using Go's concurrency -primitives to share memory through communication. -

-This should provide a starting point from which to explore the ways in which -goroutines and channels can be used to write expressive and concise concurrent -programs. -
- -
diff --git a/doc/codewalk/urlpoll.go b/doc/codewalk/urlpoll.go deleted file mode 100644 index 1fb99581f0..0000000000 --- a/doc/codewalk/urlpoll.go +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import ( - "log" - "net/http" - "time" -) - -const ( - numPollers = 2 // number of Poller goroutines to launch - pollInterval = 60 * time.Second // how often to poll each URL - statusInterval = 10 * time.Second // how often to log status to stdout - errTimeout = 10 * time.Second // back-off timeout on error -) - -var urls = []string{ - "http://www.google.com/", - "http://golang.org/", - "http://blog.golang.org/", -} - -// State represents the last-known state of a URL. -type State struct { - url string - status string -} - -// StateMonitor maintains a map that stores the state of the URLs being -// polled, and prints the current state every updateInterval nanoseconds. -// It returns a chan State to which resource state should be sent. -func StateMonitor(updateInterval time.Duration) chan<- State { - updates := make(chan State) - urlStatus := make(map[string]string) - ticker := time.NewTicker(updateInterval) - go func() { - for { - select { - case <-ticker.C: - logState(urlStatus) - case s := <-updates: - urlStatus[s.url] = s.status - } - } - }() - return updates -} - -// logState prints a state map. -func logState(s map[string]string) { - log.Println("Current state:") - for k, v := range s { - log.Printf(" %s %s", k, v) - } -} - -// Resource represents an HTTP URL to be polled by this program. -type Resource struct { - url string - errCount int -} - -// Poll executes an HTTP HEAD request for url -// and returns the HTTP status string or an error string. -func (r *Resource) Poll() string { - resp, err := http.Head(r.url) - if err != nil { - log.Println("Error", r.url, err) - r.errCount++ - return err.Error() - } - r.errCount = 0 - return resp.Status -} - -// Sleep sleeps for an appropriate interval (dependent on error state) -// before sending the Resource to done. -func (r *Resource) Sleep(done chan<- *Resource) { - time.Sleep(pollInterval + errTimeout*time.Duration(r.errCount)) - done <- r -} - -func Poller(in <-chan *Resource, out chan<- *Resource, status chan<- State) { - for r := range in { - s := r.Poll() - status <- State{r.url, s} - out <- r - } -} - -func main() { - // Create our input and output channels. - pending, complete := make(chan *Resource), make(chan *Resource) - - // Launch the StateMonitor. - status := StateMonitor(statusInterval) - - // Launch some Poller goroutines. - for i := 0; i < numPollers; i++ { - go Poller(pending, complete, status) - } - - // Send some Resources to the pending queue. - go func() { - for _, url := range urls { - pending <- &Resource{url: url} - } - }() - - for r := range complete { - go r.Sleep(pending) - } -} diff --git a/doc/contribute.html b/doc/contribute.html deleted file mode 100644 index 66a47eb07e..0000000000 --- a/doc/contribute.html +++ /dev/null @@ -1,1294 +0,0 @@ - - -

-The Go project welcomes all contributors. -

- -

-This document is a guide to help you through the process -of contributing to the Go project, which is a little different -from that used by other open source projects. -We assume you have a basic understanding of Git and Go. -

- -

-In addition to the information here, the Go community maintains a -CodeReview wiki page. -Feel free to contribute to the wiki as you learn the review process. -

- -

-Note that the gccgo front end lives elsewhere; -see Contributing to gccgo. -

- -

Becoming a contributor

- -

Overview

- -

-The first step is registering as a Go contributor and configuring your environment. -Here is a checklist of the required steps to follow: -

- -
    -
  • -Step 0: Decide on a single Google Account you will be using to contribute to Go. -Use that account for all the following steps and make sure that git -is configured to create commits with that account's e-mail address. -
  • -
  • -Step 1: Sign and submit a -CLA (Contributor License Agreement). -
  • -
  • -Step 2: Configure authentication credentials for the Go Git repository. -Visit go.googlesource.com, click -"Generate Password" in the page's top right menu bar, and follow the -instructions. -
  • -
  • -Step 3: Register for Gerrit, the code review tool used by the Go team, -by visiting this page. -The CLA and the registration need to be done only once for your account. -
  • -
  • -Step 4: Install git-codereview by running -go get -u golang.org/x/review/git-codereview -
  • -
- -

-If you prefer, there is an automated tool that walks through these steps. -Just run: -

- -
-$ go get -u golang.org/x/tools/cmd/go-contrib-init
-$ cd /code/to/edit
-$ go-contrib-init
-
- -

-The rest of this chapter elaborates on these instructions. -If you have completed the steps above (either manually or through the tool), jump to -Before contributing code. -

- -

Step 0: Select a Google Account

- -

-A contribution to Go is made through a Google account with a specific -e-mail address. -Make sure to use the same account throughout the process and -for all your subsequent contributions. -You may need to decide whether to use a personal address or a corporate address. -The choice will depend on who -will own the copyright for the code that you will be writing -and submitting. -You might want to discuss this topic with your employer before deciding which -account to use. -

- -

-Google accounts can either be Gmail e-mail accounts, G Suite organization accounts, or -accounts associated with an external e-mail address. -For instance, if you need to use -an existing corporate e-mail that is not managed through G Suite, you can create -an account associated -with your existing -e-mail address. -

- -

-You also need to make sure that your Git tool is configured to create commits -using your chosen e-mail address. -You can either configure Git globally -(as a default for all projects), or locally (for a single specific project). -You can check the current configuration with this command: -

- -
-$ git config --global user.email  # check current global config
-$ git config user.email           # check current local config
-
- -

-To change the configured address: -

- -
-$ git config --global user.email name@example.com   # change global config
-$ git config user.email name@example.com            # change local config
-
- - -

Step 1: Contributor License Agreement

- -

-Before sending your first change to the Go project -you must have completed one of the following two CLAs. -Which CLA you should sign depends on who owns the copyright to your work. -

- - - -

-You can check your currently signed agreements and sign new ones at -the Google Developers -Contributor License Agreements website. -If the copyright holder for your contribution has already completed the -agreement in connection with another Google open source project, -it does not need to be completed again. -

- -

-If the copyright holder for the code you are submitting changes—for example, -if you start contributing code on behalf of a new company—please send mail -to the golang-dev -mailing list. -This will let us know the situation so we can make sure an appropriate agreement is -completed and update the AUTHORS file. -

- - -

Step 2: Configure git authentication

- -

-The main Go repository is located at -go.googlesource.com, -a Git server hosted by Google. -Authentication on the web server is made through your Google account, but -you also need to configure git on your computer to access it. -Follow these steps: -

- -
    -
  1. -Visit go.googlesource.com -and click on "Generate Password" in the page's top right menu bar. -You will be redirected to accounts.google.com to sign in. -
  2. -
  3. -After signing in, you will be taken to a page with the title "Configure Git". -This page contains a personalized script that when run locally will configure Git -to hold your unique authentication key. -This key is paired with one that is generated and stored on the server, -analogous to how SSH keys work. -
  4. -
  5. -Copy and run this script locally in your terminal to store your secret -authentication token in a .gitcookies file. -If you are using a Windows computer and running cmd, -you should instead follow the instructions in the yellow box to run the command; -otherwise run the regular script. -
  6. -
- -

Step 3: Create a Gerrit account

- -

-Gerrit is an open-source tool used by Go maintainers to discuss and review -code submissions. -

- -

-To register your account, visit -go-review.googlesource.com/login/ and sign in once using the same Google Account you used above. -

- -

Step 4: Install the git-codereview command

- -

-Changes to Go must be reviewed before they are accepted, no matter who makes the change. -A custom git command called git-codereview -simplifies sending changes to Gerrit. -

- -

-Install the git-codereview command by running, -

- -
-$ go get -u golang.org/x/review/git-codereview
-
- -

-Make sure git-codereview is installed in your shell path, so that the -git command can find it. -Check that -

- -
-$ git codereview help
-
- -

-prints help text, not an error. If it prints an error, make sure that -$GOPATH/bin is in your $PATH. -

- -

-On Windows, when using git-bash you must make sure that -git-codereview.exe is in your git exec-path. -Run git --exec-path to discover the right location then create a -symbolic link or just copy the executable from $GOPATH/bin to this -directory. -

- - -

Before contributing code

- -

-The project welcomes code patches, but to make sure things are well -coordinated you should discuss any significant change before starting -the work. -It's recommended that you signal your intention to contribute in the -issue tracker, either by filing -a new issue or by claiming -an existing one. -

- -

Where to contribute

- -

-The Go project consists of the main -go repository, which contains the -source code for the Go language, as well as many golang.org/x/... repostories. -These contain the various tools and infrastructure that support Go. For -example, golang.org/x/pkgsite -is for pkg.go.dev, -golang.org/x/playground -is for the Go playground, and -golang.org/x/tools contains -a variety of Go tools, including the Go language server, -gopls. You can see a -list of all the golang.org/x/... repositories on -go.googlesource.com. -

- -

Check the issue tracker

- -

-Whether you already know what contribution to make, or you are searching for -an idea, the issue tracker is -always the first place to go. -Issues are triaged to categorize them and manage the workflow. -

- -

-The majority of the golang.org/x/... repos also use the main Go -issue tracker. However, a few of these repositories manage their issues -separately, so please be sure to check the right tracker for the repository to -which you would like to contribute. -

- -

-Most issues will be marked with one of the following workflow labels: -

- -
    -
  • - NeedsInvestigation: The issue is not fully understood - and requires analysis to understand the root cause. -
  • -
  • - NeedsDecision: the issue is relatively well understood, but the - Go team hasn't yet decided the best way to address it. - It would be better to wait for a decision before writing code. - If you are interested in working on an issue in this state, - feel free to "ping" maintainers in the issue's comments - if some time has passed without a decision. -
  • -
  • - NeedsFix: the issue is fully understood and code can be written - to fix it. -
  • -
- -

-You can use GitHub's search functionality to find issues to help out with. Examples: -

- - - -

Open an issue for any new problem

- -

-Excluding very trivial changes, all contributions should be connected -to an existing issue. -Feel free to open one and discuss your plans. -This process gives everyone a chance to validate the design, -helps prevent duplication of effort, -and ensures that the idea fits inside the goals for the language and tools. -It also checks that the design is sound before code is written; -the code review tool is not the place for high-level discussions. -

- -

-When planning work, please note that the Go project follows a six-month development cycle -for the main Go repository. The latter half of each cycle is a three-month -feature freeze during which only bug fixes and documentation updates are -accepted. New contributions can be sent during a feature freeze, but they will -not be merged until the freeze is over. The freeze applies to the entire main -repository as well as to the code in golang.org/x/... repositories that is -needed to build the binaries included in the release. See the lists of packages -vendored into -the standard library -and the go command. -

- -

-Significant changes to the language, libraries, or tools must go -through the -change proposal process -before they can be accepted. -

- -

-Sensitive security-related issues (only!) should be reported to security@golang.org. -

- -

Sending a change via GitHub

- -

-First-time contributors that are already familiar with the -GitHub flow -are encouraged to use the same process for Go contributions. -Even though Go -maintainers use Gerrit for code review, a bot called Gopherbot has been created to sync -GitHub pull requests to Gerrit. -

- -

-Open a pull request as you normally would. -Gopherbot will create a corresponding Gerrit change and post a link to -it on your GitHub pull request; updates to the pull request will also -get reflected in the Gerrit change. -When somebody comments on the change, their comment will be also -posted in your pull request, so you will get a notification. -

- -

-Some things to keep in mind: -

- -
    -
  • -To update the pull request with new code, just push it to the branch; you can either -add more commits, or rebase and force-push (both styles are accepted). -
  • -
  • -If the request is accepted, all commits will be squashed, and the final -commit description will be composed by concatenating the pull request's -title and description. -The individual commits' descriptions will be discarded. -See Writing good commit messages for some -suggestions. -
  • -
  • -Gopherbot is unable to sync line-by-line codereview into GitHub: only the -contents of the overall comment on the request will be synced. -Remember you can always visit Gerrit to see the fine-grained review. -
  • -
- -

Sending a change via Gerrit

- -

-It is not possible to fully sync Gerrit and GitHub, at least at the moment, -so we recommend learning Gerrit. -It's different but powerful and familiarity with it will help you understand -the flow. -

- -

Overview

- -

-This is an overview of the overall process: -

- -
    -
  • -Step 1: Clone the source code from go.googlesource.com and -make sure it's stable by compiling and testing it once. - -

    If you're making a change to the -main Go repository:

    - -
    -$ git clone https://go.googlesource.com/go
    -$ cd go/src
    -$ ./all.bash                                # compile and test
    -
    - -

    -If you're making a change to one of the golang.org/x/... repositories -(golang.org/x/tools, -in this example): -

    - -
    -$ git clone https://go.googlesource.com/tools
    -$ cd tools
    -$ go test ./...                             # compile and test
    -
    -
  • - -
  • -Step 2: Prepare changes in a new branch, created from the master branch. -To commit the changes, use git codereview change; that -will create or amend a single commit in the branch. -
    -$ git checkout -b mybranch
    -$ [edit files...]
    -$ git add [files...]
    -$ git codereview change   # create commit in the branch
    -$ [edit again...]
    -$ git add [files...]
    -$ git codereview change   # amend the existing commit with new changes
    -$ [etc.]
    -
    -
  • - -
  • -Step 3: Test your changes, either by running the tests in the package -you edited or by re-running all.bash. - -

    In the main Go repository:

    -
    -$ ./all.bash    # recompile and test
    -
    - -

    In a golang.org/x/... repository:

    -
    -$ go test ./... # recompile and test
    -
    -
  • - -
  • -Step 4: Send the changes for review to Gerrit using git -codereview mail (which doesn't use e-mail, despite the name). -
    -$ git codereview mail     # send changes to Gerrit
    -
    -
  • - -
  • -Step 5: After a review, apply changes to the same single commit -and mail them to Gerrit again: -
    -$ [edit files...]
    -$ git add [files...]
    -$ git codereview change   # update same commit
    -$ git codereview mail     # send to Gerrit again
    -
    -
  • -
- -

-The rest of this section describes these steps in more detail. -

- - -

Step 1: Clone the source code

- -

-In addition to a recent Go installation, you need to have a local copy of the source -checked out from the correct repository. -You can check out the Go source repo onto your local file system anywhere -you want as long as it's outside your GOPATH. -Clone from go.googlesource.com (not GitHub): -

- -

Main Go repository:

-
-$ git clone https://go.googlesource.com/go
-$ cd go
-
- -

golang.org/x/... repository

-(golang.org/x/tools in this example): -
-$ git clone https://go.googlesource.com/tools
-$ cd tools
-
- -

Step 2: Prepare changes in a new branch

- -

-Each Go change must be made in a separate branch, created from the master branch. -You can use -the normal git commands to create a branch and add changes to the -staging area: -

- -
-$ git checkout -b mybranch
-$ [edit files...]
-$ git add [files...]
-
- -

-To commit changes, instead of git commit, use git codereview change. -

- -
-$ git codereview change
-(open $EDITOR)
-
- -

-You can edit the commit description in your favorite editor as usual. -The git codereview change command -will automatically add a unique Change-Id line near the bottom. -That line is used by Gerrit to match successive uploads of the same change. -Do not edit or delete it. -A Change-Id looks like this: -

- -
-Change-Id: I2fbdbffb3aab626c4b6f56348861b7909e3e8990
-
- -

-The tool also checks that you've -run go fmt over the source code, and that -the commit message follows the suggested format. -

- -

-If you need to edit the files again, you can stage the new changes and -re-run git codereview change: each subsequent -run will amend the existing commit while preserving the Change-Id. -

- -

-Make sure that you always keep a single commit in each branch. -If you add more -commits by mistake, you can use git rebase to -squash them together -into a single one. -

- - -

Step 3: Test your changes

- -

-You've written and tested your code, but -before sending code out for review, run all the tests for the whole -tree to make sure the changes don't break other packages or programs. -

- -

In the main Go repository

- -

This can be done by running all.bash:

- -
-$ cd go/src
-$ ./all.bash
-
- -

-(To build under Windows use all.bat) -

- -

-After running for a while and printing a lot of testing output, the command should finish -by printing, -

- -
-ALL TESTS PASSED
-
- -

-You can use make.bash instead of all.bash -to just build the compiler and the standard library without running the test suite. -Once the go tool is built, it will be installed as bin/go -under the directory in which you cloned the Go repository, and you can -run it directly from there. -See also -the section on how to test your changes quickly. -

- -

In the golang.org/x/... repositories

- -

-Run the tests for the entire repository -(golang.org/x/tools, -in this example): -

- -
-$ cd tools
-$ go test ./...
-
- -

-If you're concerned about the build status, -you can check the Build Dashboard. -Test failures may also be caught by the TryBots in code review. -

- -

-Some repositories, like -golang.org/x/vscode-go will -have different testing infrastructures, so always check the documentation -for the repository in which you are working. The README file in the root of the -repository will usually have this information. -

- -

Step 4: Send changes for review

- -

-Once the change is ready and tested over the whole tree, send it for review. -This is done with the mail sub-command which, despite its name, doesn't -directly mail anything; it just sends the change to Gerrit: -

- -
-$ git codereview mail
-
- -

-Gerrit assigns your change a number and URL, which git codereview mail will print, something like: -

- -
-remote: New Changes:
-remote:   https://go-review.googlesource.com/99999 math: improved Sin, Cos and Tan precision for very large arguments
-
- -

-If you get an error instead, check the -Troubleshooting mail errors section. -

- -

-If your change relates to an open GitHub issue and you have followed the -suggested commit message format, the issue will be updated in a few minutes by a bot, -linking your Gerrit change to it in the comments. -

- - -

Step 5: Revise changes after a review

- -

-Go maintainers will review your code on Gerrit, and you will get notifications via e-mail. -You can see the review on Gerrit and comment on them there. -You can also reply -using e-mail -if you prefer. -

- -

-If you need to revise your change after the review, edit the files in -the same branch you previously created, add them to the Git staging -area, and then amend the commit with -git codereview change: -

- -
-$ git codereview change     # amend current commit
-(open $EDITOR)
-$ git codereview mail       # send new changes to Gerrit
-
- -

-If you don't need to change the commit description, just save and exit from the editor. -Remember not to touch the special Change-Id line. -

- -

-Again, make sure that you always keep a single commit in each branch. -If you add more -commits by mistake, you can use git rebase to -squash them together -into a single one. -

- -

Good commit messages

- -

-Commit messages in Go follow a specific set of conventions, -which we discuss in this section. -

- -

-Here is an example of a good one: -

- -
-math: improve Sin, Cos and Tan precision for very large arguments
-
-The existing implementation has poor numerical properties for
-large arguments, so use the McGillicutty algorithm to improve
-accuracy above 1e10.
-
-The algorithm is described at https://wikipedia.org/wiki/McGillicutty_Algorithm
-
-Fixes #159
-
- -

First line

- -

-The first line of the change description is conventionally a short one-line -summary of the change, prefixed by the primary affected package. -

- -

-A rule of thumb is that it should be written so to complete the sentence -"This change modifies Go to _____." -That means it does not start with a capital letter, is not a complete sentence, -and actually summarizes the result of the change. -

- -

-Follow the first line by a blank line. -

- -

Main content

- -

-The rest of the description elaborates and should provide context for the -change and explain what it does. -Write in complete sentences with correct punctuation, just like -for your comments in Go. -Don't use HTML, Markdown, or any other markup language. -

- -

-Add any relevant information, such as benchmark data if the change -affects performance. -The benchstat -tool is conventionally used to format -benchmark data for change descriptions. -

- -

Referencing issues

- -

-The special notation "Fixes #12345" associates the change with issue 12345 in the -Go issue tracker. -When this change is eventually applied, the issue -tracker will automatically mark the issue as fixed. -

- -

-If the change is a partial step towards the resolution of the issue, -write "Updates #12345" instead. -This will leave a comment in the issue linking back to the change in -Gerrit, but it will not close the issue when the change is applied. -

- -

-If you are sending a change against a golang.org/x/... repository, you must use -the fully-qualified syntax supported by GitHub to make sure the change is -linked to the issue in the main repository, not the x/ repository. -Most issues are tracked in the main repository's issue tracker. -The correct form is "Fixes golang/go#159". -

- - -

The review process

- -

-This section explains the review process in detail and how to approach -reviews after a change has been mailed. -

- - -

Common beginner mistakes

- -

-When a change is sent to Gerrit, it is usually triaged within a few days. -A maintainer will have a look and provide some initial review that for first-time -contributors usually focuses on basic cosmetics and common mistakes. -These include things like: -

- -
    -
  • -Commit message not following the suggested -format. -
  • - -
  • -The lack of a linked GitHub issue. -The vast majority of changes -require a linked issue that describes the bug or the feature that the change -fixes or implements, and consensus should have been reached on the tracker -before proceeding with it. -Gerrit reviews do not discuss the merit of the change, -just its implementation. -
    -Only trivial or cosmetic changes will be accepted without an associated issue. -
  • - -
  • -Change sent during the freeze phase of the development cycle, when the tree -is closed for general changes. -In this case, -a maintainer might review the code with a line such as R=go1.12, -which means that it will be reviewed later when the tree opens for a new -development window. -You can add R=go1.XX as a comment yourself -if you know that it's not the correct time frame for the change. -
  • -
- -

Trybots

- -

-After an initial reading of your change, maintainers will trigger trybots, -a cluster of servers that will run the full test suite on several different -architectures. -Most trybots complete in a few minutes, at which point a link will -be posted in Gerrit where you can see the results. -

- -

-If the trybot run fails, follow the link and check the full logs of the -platforms on which the tests failed. -Try to understand what broke, update your patch to fix it, and upload again. -Maintainers will trigger a new trybot run to see -if the problem was fixed. -

- -

-Sometimes, the tree can be broken on some platforms for a few hours; if -the failure reported by the trybot doesn't seem related to your patch, go to the -Build Dashboard and check if the same -failure appears in other recent commits on the same platform. -In this case, -feel free to write a comment in Gerrit to mention that the failure is -unrelated to your change, to help maintainers understand the situation. -

- -

Reviews

- -

-The Go community values very thorough reviews. -Think of each review comment like a ticket: you are expected to somehow "close" it -by acting on it, either by implementing the suggestion or convincing the -reviewer otherwise. -

- -

-After you update the change, go through the review comments and make sure -to reply to every one. -You can click the "Done" button to reply -indicating that you've implemented the reviewer's suggestion; otherwise, -click on "Reply" and explain why you have not, or what you have done instead. -

- -

-It is perfectly normal for changes to go through several round of reviews, -with one or more reviewers making new comments every time -and then waiting for an updated change before reviewing again. -This cycle happens even for experienced contributors, so -don't be discouraged by it. -

- -

Voting conventions

- -

-As they near a decision, reviewers will make a "vote" on your change. -The Gerrit voting system involves an integer in the range -2 to +2: -

- -
    -
  • - +2 The change is approved for being merged. - Only Go maintainers can cast a +2 vote. -
  • -
  • - +1 The change looks good, but either the reviewer is requesting - minor changes before approving it, or they are not a maintainer and cannot - approve it, but would like to encourage an approval. -
  • -
  • - -1 The change is not good the way it is but might be fixable. - A -1 vote will always have a comment explaining why the change is unacceptable. -
  • -
  • - -2 The change is blocked by a maintainer and cannot be approved. - Again, there will be a comment explaining the decision. -
  • -
- -

-At least two maintainers must approve of the change, and at least one -of those maintainers must +2 the change. -The second maintainer may cast a vote of Trust+1, meaning that the -change looks basically OK, but that the maintainer hasn't done the -detailed review required for a +2 vote. -

- -

Submitting an approved change

- -

-After the code has been +2'ed and Trust+1'ed, an approver will -apply it to the master branch using the Gerrit user interface. -This is called "submitting the change". -

- -

-The two steps (approving and submitting) are separate because in some cases maintainers -may want to approve it but not to submit it right away (for instance, -the tree could be temporarily frozen). -

- -

-Submitting a change checks it into the repository. -The change description will include a link to the code review, -which will be updated with a link to the change -in the repository. -Since the method used to integrate the changes is Git's "Cherry Pick", -the commit hashes in the repository will be changed by -the submit operation. -

- -

-If your change has been approved for a few days without being -submitted, feel free to write a comment in Gerrit requesting -submission. -

- - -

More information

- -

-In addition to the information here, the Go community maintains a CodeReview wiki page. -Feel free to contribute to this page as you learn more about the review process. -

- - - -

Miscellaneous topics

- -

-This section collects a number of other comments that are -outside the issue/edit/code review/submit process itself. -

- - - - -

-Files in the Go repository don't list author names, both to avoid clutter -and to avoid having to keep the lists up to date. -Instead, your name will appear in the -change log and in the CONTRIBUTORS file and perhaps the AUTHORS file. -These files are automatically generated from the commit logs periodically. -The AUTHORS file defines who “The Go -Authors”—the copyright holders—are. -

- -

-New files that you contribute should use the standard copyright header: -

- -
-// Copyright 2021 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
- -

-(Use the current year if you're reading this in 2022 or beyond.) -Files in the repository are copyrighted the year they are added. -Do not update the copyright year on files that you change. -

- - - - -

Troubleshooting mail errors

- -

-The most common way that the git codereview mail -command fails is because the e-mail address in the commit does not match the one -that you used during the registration process. - -
-If you see something like... -

- -
-remote: Processing changes: refs: 1, done
-remote:
-remote: ERROR:  In commit ab13517fa29487dcf8b0d48916c51639426c5ee9
-remote: ERROR:  author email address XXXXXXXXXXXXXXXXXXX
-remote: ERROR:  does not match your user account.
-
- -

-you need to configure Git for this repository to use the -e-mail address that you registered with. -To change the e-mail address to ensure this doesn't happen again, run: -

- -
-$ git config user.email email@address.com
-
- -

-Then change the commit to use this alternative e-mail address with this command: -

- -
-$ git commit --amend --author="Author Name <email@address.com>"
-
- -

-Then retry by running: -

- -
-$ git codereview mail
-
- - -

Quickly testing your changes

- -

-Running all.bash for every single change to the code tree -is burdensome. -Even though it is strongly suggested to run it before -sending a change, during the normal development cycle you may want -to compile and test only the package you are developing. -

- -
    -
  • -In general, you can run make.bash instead of all.bash -to only rebuild the Go tool chain without running the whole test suite. -Or you -can run run.bash to only run the whole test suite without rebuilding -the tool chain. -You can think of all.bash as make.bash -followed by run.bash. -
  • - -
  • -In this section, we'll call the directory into which you cloned the Go repository $GODIR. -The go tool built by $GODIR/src/make.bash will be installed -in $GODIR/bin/go and you -can invoke it to test your code. -For instance, if you -have modified the compiler and you want to test how it affects the -test suite of your own project, just run go test -using it: - -
    -$ cd <MYPROJECTDIR>
    -$ $GODIR/bin/go test
    -
    -
  • - -
  • -If you're changing the standard library, you probably don't need to rebuild -the compiler: you can just run the tests for the package you've changed. -You can do that either with the Go version you normally use, or -with the Go compiler built from your clone (which is -sometimes required because the standard library code you're modifying -might require a newer version than the stable one you have installed). - -
    -$ cd $GODIR/src/crypto/sha1
    -$ [make changes...]
    -$ $GODIR/bin/go test .
    -
    -
  • - -
  • -If you're modifying the compiler itself, you can just recompile -the compile tool (which is the internal binary invoked -by go build to compile each single package). -After that, you will want to test it by compiling or running something. - -
    -$ cd $GODIR/src
    -$ [make changes...]
    -$ $GODIR/bin/go install cmd/compile
    -$ $GODIR/bin/go build [something...]   # test the new compiler
    -$ $GODIR/bin/go run [something...]     # test the new compiler
    -$ $GODIR/bin/go test [something...]    # test the new compiler
    -
    - -The same applies to other internal tools of the Go tool chain, -such as asm, cover, link, and so on. -Just recompile and install the tool using go -install cmd/<TOOL> and then use -the built Go binary to test it. -
  • - -
  • -In addition to the standard per-package tests, there is a top-level -test suite in $GODIR/test that contains -several black-box and regression tests. -The test suite is run -by all.bash but you can also run it manually: - -
    -$ cd $GODIR/test
    -$ $GODIR/bin/go run run.go
    -
    -
- - -

Specifying a reviewer / CCing others

- -

-Unless explicitly told otherwise, such as in the discussion leading -up to sending in the change, it's better not to specify a reviewer. -All changes are automatically CC'ed to the -golang-codereviews@googlegroups.com -mailing list. -If this is your first ever change, there may be a moderation -delay before it appears on the mailing list, to prevent spam. -

- -

-You can specify a reviewer or CC interested parties -using the -r or -cc options. -Both accept a comma-separated list of e-mail addresses: -

- -
-$ git codereview mail -r joe@golang.org -cc mabel@example.com,math-nuts@swtch.com
-
- - -

Synchronize your client

- -

-While you were working, others might have submitted changes to the repository. -To update your local branch, run -

- -
-$ git codereview sync
-
- -

-(Under the covers this runs -git pull -r.) -

- - -

Reviewing code by others

- -

-As part of the review process reviewers can propose changes directly (in the -GitHub workflow this would be someone else attaching commits to a pull request). - -You can import these changes proposed by someone else into your local Git repository. -On the Gerrit review page, click the "Download ▼" link in the upper right -corner, copy the "Checkout" command and run it from your local Git repo. -It will look something like this: -

- -
-$ git fetch https://go.googlesource.com/review refs/changes/21/13245/1 && git checkout FETCH_HEAD
-
- -

-To revert, change back to the branch you were working in. -

- - -

Set up git aliases

- -

-The git-codereview command can be run directly from the shell -by typing, for instance, -

- -
-$ git codereview sync
-
- -

-but it is more convenient to set up aliases for git-codereview's own -subcommands, so that the above becomes, -

- -
-$ git sync
-
- -

-The git-codereview subcommands have been chosen to be distinct from -Git's own, so it's safe to define these aliases. -To install them, copy this text into your -Git configuration file (usually .gitconfig in your home directory): -

- -
-[alias]
-	change = codereview change
-	gofmt = codereview gofmt
-	mail = codereview mail
-	pending = codereview pending
-	submit = codereview submit
-	sync = codereview sync
-
- - -

Sending multiple dependent changes

- -

-Advanced users may want to stack up related commits in a single branch. -Gerrit allows for changes to be dependent on each other, forming such a dependency chain. -Each change will need to be approved and submitted separately but the dependency -will be visible to reviewers. -

- -

-To send out a group of dependent changes, keep each change as a different commit under -the same branch, and then run: -

- -
-$ git codereview mail HEAD
-
- -

-Make sure to explicitly specify HEAD, which is usually not required when sending -single changes. More details can be found in the git-codereview documentation. -

diff --git a/doc/debugging_with_gdb.html b/doc/debugging_with_gdb.html deleted file mode 100644 index e1fb292f06..0000000000 --- a/doc/debugging_with_gdb.html +++ /dev/null @@ -1,554 +0,0 @@ - - - - - -

-The following instructions apply to the standard toolchain -(the gc Go compiler and tools). -Gccgo has native gdb support. -

-

-Note that -Delve is a better -alternative to GDB when debugging Go programs built with the standard -toolchain. It understands the Go runtime, data structures, and -expressions better than GDB. Delve currently supports Linux, OSX, -and Windows on amd64. -For the most up-to-date list of supported platforms, please see - - the Delve documentation. -

-
- -

-GDB does not understand Go programs well. -The stack management, threading, and runtime contain aspects that differ -enough from the execution model GDB expects that they can confuse -the debugger and cause incorrect results even when the program is -compiled with gccgo. -As a consequence, although GDB can be useful in some situations (e.g., -debugging Cgo code, or debugging the runtime itself), it is not -a reliable debugger for Go programs, particularly heavily concurrent -ones. Moreover, it is not a priority for the Go project to address -these issues, which are difficult. -

- -

-In short, the instructions below should be taken only as a guide to how -to use GDB when it works, not as a guarantee of success. - -Besides this overview you might want to consult the -GDB manual. -

- -

-

- -

Introduction

- -

-When you compile and link your Go programs with the gc toolchain -on Linux, macOS, FreeBSD or NetBSD, the resulting binaries contain DWARFv4 -debugging information that recent versions (≥7.5) of the GDB debugger can -use to inspect a live process or a core dump. -

- -

-Pass the '-w' flag to the linker to omit the debug information -(for example, go build -ldflags=-w prog.go). -

- -

-The code generated by the gc compiler includes inlining of -function invocations and registerization of variables. These optimizations -can sometimes make debugging with gdb harder. -If you find that you need to disable these optimizations, -build your program using go build -gcflags=all="-N -l". -

- -

-If you want to use gdb to inspect a core dump, you can trigger a dump -on a program crash, on systems that permit it, by setting -GOTRACEBACK=crash in the environment (see the - runtime package -documentation for more info). -

- -

Common Operations

- -
    -
  • -Show file and line number for code, set breakpoints and disassemble: -
    (gdb) list
    -(gdb) list line
    -(gdb) list file.go:line
    -(gdb) break line
    -(gdb) break file.go:line
    -(gdb) disas
    -
  • -
  • -Show backtraces and unwind stack frames: -
    (gdb) bt
    -(gdb) frame n
    -
  • -
  • -Show the name, type and location on the stack frame of local variables, -arguments and return values: -
    (gdb) info locals
    -(gdb) info args
    -(gdb) p variable
    -(gdb) whatis variable
    -
  • -
  • -Show the name, type and location of global variables: -
    (gdb) info variables regexp
    -
  • -
- - -

Go Extensions

- -

-A recent extension mechanism to GDB allows it to load extension scripts for a -given binary. The toolchain uses this to extend GDB with a handful of -commands to inspect internals of the runtime code (such as goroutines) and to -pretty print the built-in map, slice and channel types. -

- -
    -
  • -Pretty printing a string, slice, map, channel or interface: -
    (gdb) p var
    -
  • -
  • -A $len() and $cap() function for strings, slices and maps: -
    (gdb) p $len(var)
    -
  • -
  • -A function to cast interfaces to their dynamic types: -
    (gdb) p $dtype(var)
    -(gdb) iface var
    -

    Known issue: GDB can’t automatically find the dynamic -type of an interface value if its long name differs from its short name -(annoying when printing stacktraces, the pretty printer falls back to printing -the short type name and a pointer).

    -
  • -
  • -Inspecting goroutines: -
    (gdb) info goroutines
    -(gdb) goroutine n cmd
    -(gdb) help goroutine
    -For example: -
    (gdb) goroutine 12 bt
    -You can inspect all goroutines by passing all instead of a specific goroutine's ID. -For example: -
    (gdb) goroutine all bt
    -
  • -
- -

-If you'd like to see how this works, or want to extend it, take a look at src/runtime/runtime-gdb.py in -the Go source distribution. It depends on some special magic types -(hash<T,U>) and variables (runtime.m and -runtime.g) that the linker -(src/cmd/link/internal/ld/dwarf.go) ensures are described in -the DWARF code. -

- -

-If you're interested in what the debugging information looks like, run -objdump -W a.out and browse through the .debug_* -sections. -

- - -

Known Issues

- -
    -
  1. String pretty printing only triggers for type string, not for types derived -from it.
  2. -
  3. Type information is missing for the C parts of the runtime library.
  4. -
  5. GDB does not understand Go’s name qualifications and treats -"fmt.Print" as an unstructured literal with a "." -that needs to be quoted. It objects even more strongly to method names of -the form pkg.(*MyType).Meth. -
  6. As of Go 1.11, debug information is compressed by default. -Older versions of gdb, such as the one available by default on MacOS, -do not understand the compression. -You can generate uncompressed debug information by using go -build -ldflags=-compressdwarf=false. -(For convenience you can put the -ldflags option in -the GOFLAGS -environment variable so that you don't have to specify it each time.) -
  7. -
- -

Tutorial

- -

-In this tutorial we will inspect the binary of the -regexp package's unit tests. To build the binary, -change to $GOROOT/src/regexp and run go test -c. -This should produce an executable file named regexp.test. -

- - -

Getting Started

- -

-Launch GDB, debugging regexp.test: -

- -
-$ gdb regexp.test
-GNU gdb (GDB) 7.2-gg8
-Copyright (C) 2010 Free Software Foundation, Inc.
-License GPLv  3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
-Type "show copying" and "show warranty" for licensing/warranty details.
-This GDB was configured as "x86_64-linux".
-
-Reading symbols from  /home/user/go/src/regexp/regexp.test...
-done.
-Loading Go Runtime support.
-(gdb) 
-
- -

-The message "Loading Go Runtime support" means that GDB loaded the -extension from $GOROOT/src/runtime/runtime-gdb.py. -

- -

-To help GDB find the Go runtime sources and the accompanying support script, -pass your $GOROOT with the '-d' flag: -

- -
-$ gdb regexp.test -d $GOROOT
-
- -

-If for some reason GDB still can't find that directory or that script, you can load -it by hand by telling gdb (assuming you have the go sources in -~/go/): -

- -
-(gdb) source ~/go/src/runtime/runtime-gdb.py
-Loading Go Runtime support.
-
- -

Inspecting the source

- -

-Use the "l" or "list" command to inspect source code. -

- -
-(gdb) l
-
- -

-List a specific part of the source parameterizing "list" with a -function name (it must be qualified with its package name). -

- -
-(gdb) l main.main
-
- -

-List a specific file and line number: -

- -
-(gdb) l regexp.go:1
-(gdb) # Hit enter to repeat last command. Here, this lists next 10 lines.
-
- - -

Naming

- -

-Variable and function names must be qualified with the name of the packages -they belong to. The Compile function from the regexp -package is known to GDB as 'regexp.Compile'. -

- -

-Methods must be qualified with the name of their receiver types. For example, -the *Regexp type’s String method is known as -'regexp.(*Regexp).String'. -

- -

-Variables that shadow other variables are magically suffixed with a number in the debug info. -Variables referenced by closures will appear as pointers magically prefixed with '&'. -

- -

Setting breakpoints

- -

-Set a breakpoint at the TestFind function: -

- -
-(gdb) b 'regexp.TestFind'
-Breakpoint 1 at 0x424908: file /home/user/go/src/regexp/find_test.go, line 148.
-
- -

-Run the program: -

- -
-(gdb) run
-Starting program: /home/user/go/src/regexp/regexp.test
-
-Breakpoint 1, regexp.TestFind (t=0xf8404a89c0) at /home/user/go/src/regexp/find_test.go:148
-148	func TestFind(t *testing.T) {
-
- -

-Execution has paused at the breakpoint. -See which goroutines are running, and what they're doing: -

- -
-(gdb) info goroutines
-  1  waiting runtime.gosched
-* 13  running runtime.goexit
-
- -

-the one marked with the * is the current goroutine. -

- -

Inspecting the stack

- -

-Look at the stack trace for where we’ve paused the program: -

- -
-(gdb) bt  # backtrace
-#0  regexp.TestFind (t=0xf8404a89c0) at /home/user/go/src/regexp/find_test.go:148
-#1  0x000000000042f60b in testing.tRunner (t=0xf8404a89c0, test=0x573720) at /home/user/go/src/testing/testing.go:156
-#2  0x000000000040df64 in runtime.initdone () at /home/user/go/src/runtime/proc.c:242
-#3  0x000000f8404a89c0 in ?? ()
-#4  0x0000000000573720 in ?? ()
-#5  0x0000000000000000 in ?? ()
-
- -

-The other goroutine, number 1, is stuck in runtime.gosched, blocked on a channel receive: -

- -
-(gdb) goroutine 1 bt
-#0  0x000000000040facb in runtime.gosched () at /home/user/go/src/runtime/proc.c:873
-#1  0x00000000004031c9 in runtime.chanrecv (c=void, ep=void, selected=void, received=void)
- at  /home/user/go/src/runtime/chan.c:342
-#2  0x0000000000403299 in runtime.chanrecv1 (t=void, c=void) at/home/user/go/src/runtime/chan.c:423
-#3  0x000000000043075b in testing.RunTests (matchString={void (struct string, struct string, bool *, error *)}
- 0x7ffff7f9ef60, tests=  []testing.InternalTest = {...}) at /home/user/go/src/testing/testing.go:201
-#4  0x00000000004302b1 in testing.Main (matchString={void (struct string, struct string, bool *, error *)} 
- 0x7ffff7f9ef80, tests= []testing.InternalTest = {...}, benchmarks= []testing.InternalBenchmark = {...})
-at /home/user/go/src/testing/testing.go:168
-#5  0x0000000000400dc1 in main.main () at /home/user/go/src/regexp/_testmain.go:98
-#6  0x00000000004022e7 in runtime.mainstart () at /home/user/go/src/runtime/amd64/asm.s:78
-#7  0x000000000040ea6f in runtime.initdone () at /home/user/go/src/runtime/proc.c:243
-#8  0x0000000000000000 in ?? ()
-
- -

-The stack frame shows we’re currently executing the regexp.TestFind function, as expected. -

- -
-(gdb) info frame
-Stack level 0, frame at 0x7ffff7f9ff88:
- rip = 0x425530 in regexp.TestFind (/home/user/go/src/regexp/find_test.go:148); 
-    saved rip 0x430233
- called by frame at 0x7ffff7f9ffa8
- source language minimal.
- Arglist at 0x7ffff7f9ff78, args: t=0xf840688b60
- Locals at 0x7ffff7f9ff78, Previous frame's sp is 0x7ffff7f9ff88
- Saved registers:
-  rip at 0x7ffff7f9ff80
-
- -

-The command info locals lists all variables local to the function and their values, but is a bit -dangerous to use, since it will also try to print uninitialized variables. Uninitialized slices may cause gdb to try -to print arbitrary large arrays. -

- -

-The function’s arguments: -

- -
-(gdb) info args
-t = 0xf840688b60
-
- -

-When printing the argument, notice that it’s a pointer to a -Regexp value. Note that GDB has incorrectly put the * -on the right-hand side of the type name and made up a 'struct' keyword, in traditional C style. -

- -
-(gdb) p re
-(gdb) p t
-$1 = (struct testing.T *) 0xf840688b60
-(gdb) p t
-$1 = (struct testing.T *) 0xf840688b60
-(gdb) p *t
-$2 = {errors = "", failed = false, ch = 0xf8406f5690}
-(gdb) p *t->ch
-$3 = struct hchan<*testing.T>
-
- -

-That struct hchan<*testing.T> is the -runtime-internal representation of a channel. It is currently empty, -or gdb would have pretty-printed its contents. -

- -

-Stepping forward: -

- -
-(gdb) n  # execute next line
-149             for _, test := range findTests {
-(gdb)    # enter is repeat
-150                     re := MustCompile(test.pat)
-(gdb) p test.pat
-$4 = ""
-(gdb) p re
-$5 = (struct regexp.Regexp *) 0xf84068d070
-(gdb) p *re
-$6 = {expr = "", prog = 0xf840688b80, prefix = "", prefixBytes =  []uint8, prefixComplete = true, 
-  prefixRune = 0, cond = 0 '\000', numSubexp = 0, longest = false, mu = {state = 0, sema = 0}, 
-  machine =  []*regexp.machine}
-(gdb) p *re->prog
-$7 = {Inst =  []regexp/syntax.Inst = {{Op = 5 '\005', Out = 0, Arg = 0, Rune =  []int}, {Op = 
-    6 '\006', Out = 2, Arg = 0, Rune =  []int}, {Op = 4 '\004', Out = 0, Arg = 0, Rune =  []int}}, 
-  Start = 1, NumCap = 2}
-
- - -

-We can step into the Stringfunction call with "s": -

- -
-(gdb) s
-regexp.(*Regexp).String (re=0xf84068d070, noname=void) at /home/user/go/src/regexp/regexp.go:97
-97      func (re *Regexp) String() string {
-
- -

-Get a stack trace to see where we are: -

- -
-(gdb) bt
-#0  regexp.(*Regexp).String (re=0xf84068d070, noname=void)
-    at /home/user/go/src/regexp/regexp.go:97
-#1  0x0000000000425615 in regexp.TestFind (t=0xf840688b60)
-    at /home/user/go/src/regexp/find_test.go:151
-#2  0x0000000000430233 in testing.tRunner (t=0xf840688b60, test=0x5747b8)
-    at /home/user/go/src/testing/testing.go:156
-#3  0x000000000040ea6f in runtime.initdone () at /home/user/go/src/runtime/proc.c:243
-....
-
- -

-Look at the source code: -

- -
-(gdb) l
-92              mu      sync.Mutex
-93              machine []*machine
-94      }
-95
-96      // String returns the source text used to compile the regular expression.
-97      func (re *Regexp) String() string {
-98              return re.expr
-99      }
-100
-101     // Compile parses a regular expression and returns, if successful,
-
- -

Pretty Printing

- -

-GDB's pretty printing mechanism is triggered by regexp matches on type names. An example for slices: -

- -
-(gdb) p utf
-$22 =  []uint8 = {0 '\000', 0 '\000', 0 '\000', 0 '\000'}
-
- -

-Since slices, arrays and strings are not C pointers, GDB can't interpret the subscripting operation for you, but -you can look inside the runtime representation to do that (tab completion helps here): -

-
-
-(gdb) p slc
-$11 =  []int = {0, 0}
-(gdb) p slc-><TAB>
-array  slc    len    
-(gdb) p slc->array
-$12 = (int *) 0xf84057af00
-(gdb) p slc->array[1]
-$13 = 0
- - - -

-The extension functions $len and $cap work on strings, arrays and slices: -

- -
-(gdb) p $len(utf)
-$23 = 4
-(gdb) p $cap(utf)
-$24 = 4
-
- -

-Channels and maps are 'reference' types, which gdb shows as pointers to C++-like types hash<int,string>*. Dereferencing will trigger prettyprinting -

- -

-Interfaces are represented in the runtime as a pointer to a type descriptor and a pointer to a value. The Go GDB runtime extension decodes this and automatically triggers pretty printing for the runtime type. The extension function $dtype decodes the dynamic type for you (examples are taken from a breakpoint at regexp.go line 293.) -

- -
-(gdb) p i
-$4 = {str = "cbb"}
-(gdb) whatis i
-type = regexp.input
-(gdb) p $dtype(i)
-$26 = (struct regexp.inputBytes *) 0xf8400b4930
-(gdb) iface i
-regexp.input: struct regexp.inputBytes *
-
diff --git a/doc/diagnostics.html b/doc/diagnostics.html deleted file mode 100644 index 438cdce45f..0000000000 --- a/doc/diagnostics.html +++ /dev/null @@ -1,472 +0,0 @@ - - - - -

Introduction

- -

-The Go ecosystem provides a large suite of APIs and tools to -diagnose logic and performance problems in Go programs. This page -summarizes the available tools and helps Go users pick the right one -for their specific problem. -

- -

-Diagnostics solutions can be categorized into the following groups: -

- -
    -
  • Profiling: Profiling tools analyze the complexity and costs of a -Go program such as its memory usage and frequently called -functions to identify the expensive sections of a Go program.
  • -
  • Tracing: Tracing is a way to instrument code to analyze latency -throughout the lifecycle of a call or user request. Traces provide an -overview of how much latency each component contributes to the overall -latency in a system. Traces can span multiple Go processes.
  • -
  • Debugging: Debugging allows us to pause a Go program and examine -its execution. Program state and flow can be verified with debugging.
  • -
  • Runtime statistics and events: Collection and analysis of runtime stats and events -provides a high-level overview of the health of Go programs. Spikes/dips of metrics -helps us to identify changes in throughput, utilization, and performance.
  • -
- -

-Note: Some diagnostics tools may interfere with each other. For example, precise -memory profiling skews CPU profiles and goroutine blocking profiling affects scheduler -trace. Use tools in isolation to get more precise info. -

- -

Profiling

- -

-Profiling is useful for identifying expensive or frequently called sections -of code. The Go runtime provides -profiling data in the format expected by the -pprof visualization tool. -The profiling data can be collected during testing -via go test or endpoints made available from the -net/http/pprof package. Users need to collect the profiling data and use pprof tools to filter -and visualize the top code paths. -

- -

Predefined profiles provided by the runtime/pprof package:

- -
    -
  • -cpu: CPU profile determines where a program spends -its time while actively consuming CPU cycles (as opposed to while sleeping or waiting for I/O). -
  • -
  • -heap: Heap profile reports memory allocation samples; -used to monitor current and historical memory usage, and to check for memory leaks. -
  • -
  • -threadcreate: Thread creation profile reports the sections -of the program that lead the creation of new OS threads. -
  • -
  • -goroutine: Goroutine profile reports the stack traces of all current goroutines. -
  • -
  • -block: Block profile shows where goroutines block waiting on synchronization -primitives (including timer channels). Block profile is not enabled by default; -use runtime.SetBlockProfileRate to enable it. -
  • -
  • -mutex: Mutex profile reports the lock contentions. When you think your -CPU is not fully utilized due to a mutex contention, use this profile. Mutex profile -is not enabled by default, see runtime.SetMutexProfileFraction to enable it. -
  • -
- - -

What other profilers can I use to profile Go programs?

- -

-On Linux, perf tools -can be used for profiling Go programs. Perf can profile -and unwind cgo/SWIG code and kernel, so it can be useful to get insights into -native/kernel performance bottlenecks. On macOS, -Instruments -suite can be used profile Go programs. -

- -

Can I profile my production services?

- -

Yes. It is safe to profile programs in production, but enabling -some profiles (e.g. the CPU profile) adds cost. You should expect to -see performance downgrade. The performance penalty can be estimated -by measuring the overhead of the profiler before turning it on in -production. -

- -

-You may want to periodically profile your production services. -Especially in a system with many replicas of a single process, selecting -a random replica periodically is a safe option. -Select a production process, profile it for -X seconds for every Y seconds and save the results for visualization and -analysis; then repeat periodically. Results may be manually and/or automatically -reviewed to find problems. -Collection of profiles can interfere with each other, -so it is recommended to collect only a single profile at a time. -

- -

-What are the best ways to visualize the profiling data? -

- -

-The Go tools provide text, graph, and callgrind -visualization of the profile data using -go tool pprof. -Read Profiling Go programs -to see them in action. -

- -

- -
-Listing of the most expensive calls as text. -

- -

- -
-Visualization of the most expensive calls as a graph. -

- -

Weblist view displays the expensive parts of the source line by line in -an HTML page. In the following example, 530ms is spent in the -runtime.concatstrings and cost of each line is presented -in the listing.

- -

- -
-Visualization of the most expensive calls as weblist. -

- -

-Another way to visualize profile data is a flame graph. -Flame graphs allow you to move in a specific ancestry path, so you can zoom -in/out of specific sections of code. -The upstream pprof -has support for flame graphs. -

- -

- -
-Flame graphs offers visualization to spot the most expensive code-paths. -

- -

Am I restricted to the built-in profiles?

- -

-Additionally to what is provided by the runtime, Go users can create -their custom profiles via pprof.Profile -and use the existing tools to examine them. -

- -

Can I serve the profiler handlers (/debug/pprof/...) on a different path and port?

- -

-Yes. The net/http/pprof package registers its handlers to the default -mux by default, but you can also register them yourself by using the handlers -exported from the package. -

- -

-For example, the following example will serve the pprof.Profile -handler on :7777 at /custom_debug_path/profile: -

- -

-

-package main
-
-import (
-	"log"
-	"net/http"
-	"net/http/pprof"
-)
-
-func main() {
-	mux := http.NewServeMux()
-	mux.HandleFunc("/custom_debug_path/profile", pprof.Profile)
-	log.Fatal(http.ListenAndServe(":7777", mux))
-}
-
-

- -

Tracing

- -

-Tracing is a way to instrument code to analyze latency throughout the -lifecycle of a chain of calls. Go provides -golang.org/x/net/trace -package as a minimal tracing backend per Go node and provides a minimal -instrumentation library with a simple dashboard. Go also provides -an execution tracer to trace the runtime events within an interval. -

- -

Tracing enables us to:

- -
    -
  • Instrument and analyze application latency in a Go process.
  • -
  • Measure the cost of specific calls in a long chain of calls.
  • -
  • Figure out the utilization and performance improvements. -Bottlenecks are not always obvious without tracing data.
  • -
- -

-In monolithic systems, it's relatively easy to collect diagnostic data -from the building blocks of a program. All modules live within one -process and share common resources to report logs, errors, and other -diagnostic information. Once your system grows beyond a single process and -starts to become distributed, it becomes harder to follow a call starting -from the front-end web server to all of its back-ends until a response is -returned back to the user. This is where distributed tracing plays a big -role to instrument and analyze your production systems. -

- -

-Distributed tracing is a way to instrument code to analyze latency throughout -the lifecycle of a user request. When a system is distributed and when -conventional profiling and debugging tools don’t scale, you might want -to use distributed tracing tools to analyze the performance of your user -requests and RPCs. -

- -

Distributed tracing enables us to:

- -
    -
  • Instrument and profile application latency in a large system.
  • -
  • Track all RPCs within the lifecycle of a user request and see integration issues -that are only visible in production.
  • -
  • Figure out performance improvements that can be applied to our systems. -Many bottlenecks are not obvious before the collection of tracing data.
  • -
- -

The Go ecosystem provides various distributed tracing libraries per tracing system -and backend-agnostic ones.

- - -

Is there a way to automatically intercept each function call and create traces?

- -

-Go doesn’t provide a way to automatically intercept every function call and create -trace spans. You need to manually instrument your code to create, end, and annotate spans. -

- -

How should I propagate trace headers in Go libraries?

- -

-You can propagate trace identifiers and tags in the -context.Context. -There is no canonical trace key or common representation of trace headers -in the industry yet. Each tracing provider is responsible for providing propagation -utilities in their Go libraries. -

- -

-What other low-level events from the standard library or -runtime can be included in a trace? -

- -

-The standard library and runtime are trying to expose several additional APIs -to notify on low level internal events. For example, -httptrace.ClientTrace -provides APIs to follow low-level events in the life cycle of an outgoing request. -There is an ongoing effort to retrieve low-level runtime events from -the runtime execution tracer and allow users to define and record their user events. -

- -

Debugging

- -

-Debugging is the process of identifying why a program misbehaves. -Debuggers allow us to understand a program’s execution flow and current state. -There are several styles of debugging; this section will only focus on attaching -a debugger to a program and core dump debugging. -

- -

Go users mostly use the following debuggers:

- -
    -
  • -Delve: -Delve is a debugger for the Go programming language. It has -support for Go’s runtime concepts and built-in types. Delve is -trying to be a fully featured reliable debugger for Go programs. -
  • -
  • -GDB: -Go provides GDB support via the standard Go compiler and Gccgo. -The stack management, threading, and runtime contain aspects that differ -enough from the execution model GDB expects that they can confuse the -debugger, even when the program is compiled with gccgo. Even though -GDB can be used to debug Go programs, it is not ideal and may -create confusion. -
  • -
- -

How well do debuggers work with Go programs?

- -

-The gc compiler performs optimizations such as -function inlining and variable registerization. These optimizations -sometimes make debugging with debuggers harder. There is an ongoing -effort to improve the quality of the DWARF information generated for -optimized binaries. Until those improvements are available, we recommend -disabling optimizations when building the code being debugged. The following -command builds a package with no compiler optimizations: - -

-

-$ go build -gcflags=all="-N -l"
-
-

- -As part of the improvement effort, Go 1.10 introduced a new compiler -flag -dwarflocationlists. The flag causes the compiler to -add location lists that helps debuggers work with optimized binaries. -The following command builds a package with optimizations but with -the DWARF location lists: - -

-

-$ go build -gcflags="-dwarflocationlists=true"
-
-

- -

What’s the recommended debugger user interface?

- -

-Even though both delve and gdb provides CLIs, most editor integrations -and IDEs provides debugging-specific user interfaces. -

- -

Is it possible to do postmortem debugging with Go programs?

- -

-A core dump file is a file that contains the memory dump of a running -process and its process status. It is primarily used for post-mortem -debugging of a program and to understand its state -while it is still running. These two cases make debugging of core -dumps a good diagnostic aid to postmortem and analyze production -services. It is possible to obtain core files from Go programs and -use delve or gdb to debug, see the -core dump debugging -page for a step-by-step guide. -

- -

Runtime statistics and events

- -

-The runtime provides stats and reporting of internal events for -users to diagnose performance and utilization problems at the -runtime level. -

- -

-Users can monitor these stats to better understand the overall -health and performance of Go programs. -Some frequently monitored stats and states: -

- -
    -
  • runtime.ReadMemStats -reports the metrics related to heap -allocation and garbage collection. Memory stats are useful for -monitoring how much memory resources a process is consuming, -whether the process can utilize memory well, and to catch -memory leaks.
  • -
  • debug.ReadGCStats -reads statistics about garbage collection. -It is useful to see how much of the resources are spent on GC pauses. -It also reports a timeline of garbage collector pauses and pause time percentiles.
  • -
  • debug.Stack -returns the current stack trace. Stack trace -is useful to see how many goroutines are currently running, -what they are doing, and whether they are blocked or not.
  • -
  • debug.WriteHeapDump -suspends the execution of all goroutines -and allows you to dump the heap to a file. A heap dump is a -snapshot of a Go process' memory at a given time. It contains all -allocated objects as well as goroutines, finalizers, and more.
  • -
  • runtime.NumGoroutine -returns the number of current goroutines. -The value can be monitored to see whether enough goroutines are -utilized, or to detect goroutine leaks.
  • -
- -

Execution tracer

- -

Go comes with a runtime execution tracer to capture a wide range -of runtime events. Scheduling, syscall, garbage collections, -heap size, and other events are collected by runtime and available -for visualization by the go tool trace. Execution tracer is a tool -to detect latency and utilization problems. You can examine how well -the CPU is utilized, and when networking or syscalls are a cause of -preemption for the goroutines.

- -

Tracer is useful to:

-
    -
  • Understand how your goroutines execute.
  • -
  • Understand some of the core runtime events such as GC runs.
  • -
  • Identify poorly parallelized execution.
  • -
- -

However, it is not great for identifying hot spots such as -analyzing the cause of excessive memory or CPU usage. -Use profiling tools instead first to address them.

- -

- -

- -

Above, the go tool trace visualization shows the execution started -fine, and then it became serialized. It suggests that there might -be lock contention for a shared resource that creates a bottleneck.

- -

See go tool trace -to collect and analyze runtime traces. -

- -

GODEBUG

- -

Runtime also emits events and information if -GODEBUG -environmental variable is set accordingly.

- -
    -
  • GODEBUG=gctrace=1 prints garbage collector events at -each collection, summarizing the amount of memory collected -and the length of the pause.
  • -
  • GODEBUG=inittrace=1 prints a summary of execution time and memory allocation -information for completed package initialization work.
  • -
  • GODEBUG=schedtrace=X prints scheduling events every X milliseconds.
  • -
- -

The GODEBUG environmental variable can be used to disable use of -instruction set extensions in the standard library and runtime.

- -
    -
  • GODEBUG=cpu.all=off disables the use of all optional -instruction set extensions.
  • -
  • GODEBUG=cpu.extension=off disables use of instructions from the -specified instruction set extension.
    -extension is the lower case name for the instruction set extension -such as sse41 or avx.
  • -
diff --git a/doc/editors.html b/doc/editors.html deleted file mode 100644 index e0d0c530e5..0000000000 --- a/doc/editors.html +++ /dev/null @@ -1,33 +0,0 @@ - - -

Introduction

- -

- This document lists commonly used editor plugins and IDEs from the Go ecosystem - that make Go development more productive and seamless. - A comprehensive list of editor support and IDEs for Go development is available at - the wiki. -

- -

Options

-

-The Go ecosystem provides a variety of editor plugins and IDEs to enhance your day-to-day -editing, navigation, testing, and debugging experience. -

- -
    -
  • Visual Studio Code: -Go extension provides support for the Go programming language
  • -
  • GoLand: GoLand is distributed either as a standalone IDE -or as a plugin for IntelliJ IDEA Ultimate
  • -
  • vim: vim-go plugin provides Go programming language support
  • - -

    -Note that these are only a few top solutions; a more comprehensive -community-maintained list of -IDEs and text editor plugins -is available at the Wiki. -

    diff --git a/doc/effective_go.html b/doc/effective_go.html deleted file mode 100644 index 7620402984..0000000000 --- a/doc/effective_go.html +++ /dev/null @@ -1,3673 +0,0 @@ - - -

    Introduction

    - -

    -Go is a new language. Although it borrows ideas from -existing languages, -it has unusual properties that make effective Go programs -different in character from programs written in its relatives. -A straightforward translation of a C++ or Java program into Go -is unlikely to produce a satisfactory result—Java programs -are written in Java, not Go. -On the other hand, thinking about the problem from a Go -perspective could produce a successful but quite different -program. -In other words, -to write Go well, it's important to understand its properties -and idioms. -It's also important to know the established conventions for -programming in Go, such as naming, formatting, program -construction, and so on, so that programs you write -will be easy for other Go programmers to understand. -

    - -

    -This document gives tips for writing clear, idiomatic Go code. -It augments the language specification, -the Tour of Go, -and How to Write Go Code, -all of which you -should read first. -

    - -

    Examples

    - -

    -The Go package sources -are intended to serve not -only as the core library but also as examples of how to -use the language. -Moreover, many of the packages contain working, self-contained -executable examples you can run directly from the -golang.org web site, such as -this one (if -necessary, click on the word "Example" to open it up). -If you have a question about how to approach a problem or how something -might be implemented, the documentation, code and examples in the -library can provide answers, ideas and -background. -

    - - -

    Formatting

    - -

    -Formatting issues are the most contentious -but the least consequential. -People can adapt to different formatting styles -but it's better if they don't have to, and -less time is devoted to the topic -if everyone adheres to the same style. -The problem is how to approach this Utopia without a long -prescriptive style guide. -

    - -

    -With Go we take an unusual -approach and let the machine -take care of most formatting issues. -The gofmt program -(also available as go fmt, which -operates at the package level rather than source file level) -reads a Go program -and emits the source in a standard style of indentation -and vertical alignment, retaining and if necessary -reformatting comments. -If you want to know how to handle some new layout -situation, run gofmt; if the answer doesn't -seem right, rearrange your program (or file a bug about gofmt), -don't work around it. -

    - -

    -As an example, there's no need to spend time lining up -the comments on the fields of a structure. -Gofmt will do that for you. Given the -declaration -

    - -
    -type T struct {
    -    name string // name of the object
    -    value int // its value
    -}
    -
    - -

    -gofmt will line up the columns: -

    - -
    -type T struct {
    -    name    string // name of the object
    -    value   int    // its value
    -}
    -
    - -

    -All Go code in the standard packages has been formatted with gofmt. -

    - - -

    -Some formatting details remain. Very briefly: -

    - -
    -
    Indentation
    -
    We use tabs for indentation and gofmt emits them by default. - Use spaces only if you must. -
    -
    Line length
    -
    - Go has no line length limit. Don't worry about overflowing a punched card. - If a line feels too long, wrap it and indent with an extra tab. -
    -
    Parentheses
    -
    - Go needs fewer parentheses than C and Java: control structures (if, - for, switch) do not have parentheses in - their syntax. - Also, the operator precedence hierarchy is shorter and clearer, so -
    -x<<8 + y<<16
    -
    - means what the spacing implies, unlike in the other languages. -
    -
    - -

    Commentary

    - -

    -Go provides C-style /* */ block comments -and C++-style // line comments. -Line comments are the norm; -block comments appear mostly as package comments, but -are useful within an expression or to disable large swaths of code. -

    - -

    -The program—and web server—godoc processes -Go source files to extract documentation about the contents of the -package. -Comments that appear before top-level declarations, with no intervening newlines, -are extracted along with the declaration to serve as explanatory text for the item. -The nature and style of these comments determines the -quality of the documentation godoc produces. -

    - -

    -Every package should have a package comment, a block -comment preceding the package clause. -For multi-file packages, the package comment only needs to be -present in one file, and any one will do. -The package comment should introduce the package and -provide information relevant to the package as a whole. -It will appear first on the godoc page and -should set up the detailed documentation that follows. -

    - -
    -/*
    -Package regexp implements a simple library for regular expressions.
    -
    -The syntax of the regular expressions accepted is:
    -
    -    regexp:
    -        concatenation { '|' concatenation }
    -    concatenation:
    -        { closure }
    -    closure:
    -        term [ '*' | '+' | '?' ]
    -    term:
    -        '^'
    -        '$'
    -        '.'
    -        character
    -        '[' [ '^' ] character-ranges ']'
    -        '(' regexp ')'
    -*/
    -package regexp
    -
    - -

    -If the package is simple, the package comment can be brief. -

    - -
    -// Package path implements utility routines for
    -// manipulating slash-separated filename paths.
    -
    - -

    -Comments do not need extra formatting such as banners of stars. -The generated output may not even be presented in a fixed-width font, so don't depend -on spacing for alignment—godoc, like gofmt, -takes care of that. -The comments are uninterpreted plain text, so HTML and other -annotations such as _this_ will reproduce verbatim and should -not be used. -One adjustment godoc does do is to display indented -text in a fixed-width font, suitable for program snippets. -The package comment for the -fmt package uses this to good effect. -

    - -

    -Depending on the context, godoc might not even -reformat comments, so make sure they look good straight up: -use correct spelling, punctuation, and sentence structure, -fold long lines, and so on. -

    - -

    -Inside a package, any comment immediately preceding a top-level declaration -serves as a doc comment for that declaration. -Every exported (capitalized) name in a program should -have a doc comment. -

    - -

    -Doc comments work best as complete sentences, which allow -a wide variety of automated presentations. -The first sentence should be a one-sentence summary that -starts with the name being declared. -

    - -
    -// Compile parses a regular expression and returns, if successful,
    -// a Regexp that can be used to match against text.
    -func Compile(str string) (*Regexp, error) {
    -
    - -

    -If every doc comment begins with the name of the item it describes, -you can use the doc -subcommand of the go tool -and run the output through grep. -Imagine you couldn't remember the name "Compile" but were looking for -the parsing function for regular expressions, so you ran -the command, -

    - -
    -$ go doc -all regexp | grep -i parse
    -
    - -

    -If all the doc comments in the package began, "This function...", grep -wouldn't help you remember the name. But because the package starts each -doc comment with the name, you'd see something like this, -which recalls the word you're looking for. -

    - -
    -$ go doc -all regexp | grep -i parse
    -    Compile parses a regular expression and returns, if successful, a Regexp
    -    MustCompile is like Compile but panics if the expression cannot be parsed.
    -    parsed. It simplifies safe initialization of global variables holding
    -$
    -
    - -

    -Go's declaration syntax allows grouping of declarations. -A single doc comment can introduce a group of related constants or variables. -Since the whole declaration is presented, such a comment can often be perfunctory. -

    - -
    -// Error codes returned by failures to parse an expression.
    -var (
    -    ErrInternal      = errors.New("regexp: internal error")
    -    ErrUnmatchedLpar = errors.New("regexp: unmatched '('")
    -    ErrUnmatchedRpar = errors.New("regexp: unmatched ')'")
    -    ...
    -)
    -
    - -

    -Grouping can also indicate relationships between items, -such as the fact that a set of variables is protected by a mutex. -

    - -
    -var (
    -    countLock   sync.Mutex
    -    inputCount  uint32
    -    outputCount uint32
    -    errorCount  uint32
    -)
    -
    - -

    Names

    - -

    -Names are as important in Go as in any other language. -They even have semantic effect: -the visibility of a name outside a package is determined by whether its -first character is upper case. -It's therefore worth spending a little time talking about naming conventions -in Go programs. -

    - - -

    Package names

    - -

    -When a package is imported, the package name becomes an accessor for the -contents. After -

    - -
    -import "bytes"
    -
    - -

    -the importing package can talk about bytes.Buffer. It's -helpful if everyone using the package can use the same name to refer to -its contents, which implies that the package name should be good: -short, concise, evocative. By convention, packages are given -lower case, single-word names; there should be no need for underscores -or mixedCaps. -Err on the side of brevity, since everyone using your -package will be typing that name. -And don't worry about collisions a priori. -The package name is only the default name for imports; it need not be unique -across all source code, and in the rare case of a collision the -importing package can choose a different name to use locally. -In any case, confusion is rare because the file name in the import -determines just which package is being used. -

    - -

    -Another convention is that the package name is the base name of -its source directory; -the package in src/encoding/base64 -is imported as "encoding/base64" but has name base64, -not encoding_base64 and not encodingBase64. -

    - -

    -The importer of a package will use the name to refer to its contents, -so exported names in the package can use that fact -to avoid stutter. -(Don't use the import . notation, which can simplify -tests that must run outside the package they are testing, but should otherwise be avoided.) -For instance, the buffered reader type in the bufio package is called Reader, -not BufReader, because users see it as bufio.Reader, -which is a clear, concise name. -Moreover, -because imported entities are always addressed with their package name, bufio.Reader -does not conflict with io.Reader. -Similarly, the function to make new instances of ring.Ring—which -is the definition of a constructor in Go—would -normally be called NewRing, but since -Ring is the only type exported by the package, and since the -package is called ring, it's called just New, -which clients of the package see as ring.New. -Use the package structure to help you choose good names. -

    - -

    -Another short example is once.Do; -once.Do(setup) reads well and would not be improved by -writing once.DoOrWaitUntilDone(setup). -Long names don't automatically make things more readable. -A helpful doc comment can often be more valuable than an extra long name. -

    - -

    Getters

    - -

    -Go doesn't provide automatic support for getters and setters. -There's nothing wrong with providing getters and setters yourself, -and it's often appropriate to do so, but it's neither idiomatic nor necessary -to put Get into the getter's name. If you have a field called -owner (lower case, unexported), the getter method should be -called Owner (upper case, exported), not GetOwner. -The use of upper-case names for export provides the hook to discriminate -the field from the method. -A setter function, if needed, will likely be called SetOwner. -Both names read well in practice: -

    -
    -owner := obj.Owner()
    -if owner != user {
    -    obj.SetOwner(user)
    -}
    -
    - -

    Interface names

    - -

    -By convention, one-method interfaces are named by -the method name plus an -er suffix or similar modification -to construct an agent noun: Reader, -Writer, Formatter, -CloseNotifier etc. -

    - -

    -There are a number of such names and it's productive to honor them and the function -names they capture. -Read, Write, Close, Flush, -String and so on have -canonical signatures and meanings. To avoid confusion, -don't give your method one of those names unless it -has the same signature and meaning. -Conversely, if your type implements a method with the -same meaning as a method on a well-known type, -give it the same name and signature; -call your string-converter method String not ToString. -

    - -

    MixedCaps

    - -

    -Finally, the convention in Go is to use MixedCaps -or mixedCaps rather than underscores to write -multiword names. -

    - -

    Semicolons

    - -

    -Like C, Go's formal grammar uses semicolons to terminate statements, -but unlike in C, those semicolons do not appear in the source. -Instead the lexer uses a simple rule to insert semicolons automatically -as it scans, so the input text is mostly free of them. -

    - -

    -The rule is this. If the last token before a newline is an identifier -(which includes words like int and float64), -a basic literal such as a number or string constant, or one of the -tokens -

    -
    -break continue fallthrough return ++ -- ) }
    -
    -

    -the lexer always inserts a semicolon after the token. -This could be summarized as, “if the newline comes -after a token that could end a statement, insert a semicolon”. -

    - -

    -A semicolon can also be omitted immediately before a closing brace, -so a statement such as -

    -
    -    go func() { for { dst <- <-src } }()
    -
    -

    -needs no semicolons. -Idiomatic Go programs have semicolons only in places such as -for loop clauses, to separate the initializer, condition, and -continuation elements. They are also necessary to separate multiple -statements on a line, should you write code that way. -

    - -

    -One consequence of the semicolon insertion rules -is that you cannot put the opening brace of a -control structure (if, for, switch, -or select) on the next line. If you do, a semicolon -will be inserted before the brace, which could cause unwanted -effects. Write them like this -

    - -
    -if i < f() {
    -    g()
    -}
    -
    -

    -not like this -

    -
    -if i < f()  // wrong!
    -{           // wrong!
    -    g()
    -}
    -
    - - -

    Control structures

    - -

    -The control structures of Go are related to those of C but differ -in important ways. -There is no do or while loop, only a -slightly generalized -for; -switch is more flexible; -if and switch accept an optional -initialization statement like that of for; -break and continue statements -take an optional label to identify what to break or continue; -and there are new control structures including a type switch and a -multiway communications multiplexer, select. -The syntax is also slightly different: -there are no parentheses -and the bodies must always be brace-delimited. -

    - -

    If

    - -

    -In Go a simple if looks like this: -

    -
    -if x > 0 {
    -    return y
    -}
    -
    - -

    -Mandatory braces encourage writing simple if statements -on multiple lines. It's good style to do so anyway, -especially when the body contains a control statement such as a -return or break. -

    - -

    -Since if and switch accept an initialization -statement, it's common to see one used to set up a local variable. -

    - -
    -if err := file.Chmod(0664); err != nil {
    -    log.Print(err)
    -    return err
    -}
    -
    - -

    -In the Go libraries, you'll find that -when an if statement doesn't flow into the next statement—that is, -the body ends in break, continue, -goto, or return—the unnecessary -else is omitted. -

    - -
    -f, err := os.Open(name)
    -if err != nil {
    -    return err
    -}
    -codeUsing(f)
    -
    - -

    -This is an example of a common situation where code must guard against a -sequence of error conditions. The code reads well if the -successful flow of control runs down the page, eliminating error cases -as they arise. Since error cases tend to end in return -statements, the resulting code needs no else statements. -

    - -
    -f, err := os.Open(name)
    -if err != nil {
    -    return err
    -}
    -d, err := f.Stat()
    -if err != nil {
    -    f.Close()
    -    return err
    -}
    -codeUsing(f, d)
    -
    - - -

    Redeclaration and reassignment

    - -

    -An aside: The last example in the previous section demonstrates a detail of how the -:= short declaration form works. -The declaration that calls os.Open reads, -

    - -
    -f, err := os.Open(name)
    -
    - -

    -This statement declares two variables, f and err. -A few lines later, the call to f.Stat reads, -

    - -
    -d, err := f.Stat()
    -
    - -

    -which looks as if it declares d and err. -Notice, though, that err appears in both statements. -This duplication is legal: err is declared by the first statement, -but only re-assigned in the second. -This means that the call to f.Stat uses the existing -err variable declared above, and just gives it a new value. -

    - -

    -In a := declaration a variable v may appear even -if it has already been declared, provided: -

    - -
      -
    • this declaration is in the same scope as the existing declaration of v -(if v is already declared in an outer scope, the declaration will create a new variable §),
    • -
    • the corresponding value in the initialization is assignable to v, and
    • -
    • there is at least one other variable that is created by the declaration.
    • -
    - -

    -This unusual property is pure pragmatism, -making it easy to use a single err value, for example, -in a long if-else chain. -You'll see it used often. -

    - -

    -§ It's worth noting here that in Go the scope of function parameters and return values -is the same as the function body, even though they appear lexically outside the braces -that enclose the body. -

    - -

    For

    - -

    -The Go for loop is similar to—but not the same as—C's. -It unifies for -and while and there is no do-while. -There are three forms, only one of which has semicolons. -

    -
    -// Like a C for
    -for init; condition; post { }
    -
    -// Like a C while
    -for condition { }
    -
    -// Like a C for(;;)
    -for { }
    -
    - -

    -Short declarations make it easy to declare the index variable right in the loop. -

    -
    -sum := 0
    -for i := 0; i < 10; i++ {
    -    sum += i
    -}
    -
    - -

    -If you're looping over an array, slice, string, or map, -or reading from a channel, a range clause can -manage the loop. -

    -
    -for key, value := range oldMap {
    -    newMap[key] = value
    -}
    -
    - -

    -If you only need the first item in the range (the key or index), drop the second: -

    -
    -for key := range m {
    -    if key.expired() {
    -        delete(m, key)
    -    }
    -}
    -
    - -

    -If you only need the second item in the range (the value), use the blank identifier, an underscore, to discard the first: -

    -
    -sum := 0
    -for _, value := range array {
    -    sum += value
    -}
    -
    - -

    -The blank identifier has many uses, as described in a later section. -

    - -

    -For strings, the range does more work for you, breaking out individual -Unicode code points by parsing the UTF-8. -Erroneous encodings consume one byte and produce the -replacement rune U+FFFD. -(The name (with associated builtin type) rune is Go terminology for a -single Unicode code point. -See the language specification -for details.) -The loop -

    -
    -for pos, char := range "日本\x80語" { // \x80 is an illegal UTF-8 encoding
    -    fmt.Printf("character %#U starts at byte position %d\n", char, pos)
    -}
    -
    -

    -prints -

    -
    -character U+65E5 '日' starts at byte position 0
    -character U+672C '本' starts at byte position 3
    -character U+FFFD '�' starts at byte position 6
    -character U+8A9E '語' starts at byte position 7
    -
    - -

    -Finally, Go has no comma operator and ++ and -- -are statements not expressions. -Thus if you want to run multiple variables in a for -you should use parallel assignment (although that precludes ++ and --). -

    -
    -// Reverse a
    -for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
    -    a[i], a[j] = a[j], a[i]
    -}
    -
    - -

    Switch

    - -

    -Go's switch is more general than C's. -The expressions need not be constants or even integers, -the cases are evaluated top to bottom until a match is found, -and if the switch has no expression it switches on -true. -It's therefore possible—and idiomatic—to write an -if-else-if-else -chain as a switch. -

    - -
    -func unhex(c byte) byte {
    -    switch {
    -    case '0' <= c && c <= '9':
    -        return c - '0'
    -    case 'a' <= c && c <= 'f':
    -        return c - 'a' + 10
    -    case 'A' <= c && c <= 'F':
    -        return c - 'A' + 10
    -    }
    -    return 0
    -}
    -
    - -

    -There is no automatic fall through, but cases can be presented -in comma-separated lists. -

    -
    -func shouldEscape(c byte) bool {
    -    switch c {
    -    case ' ', '?', '&', '=', '#', '+', '%':
    -        return true
    -    }
    -    return false
    -}
    -
    - -

    -Although they are not nearly as common in Go as some other C-like -languages, break statements can be used to terminate -a switch early. -Sometimes, though, it's necessary to break out of a surrounding loop, -not the switch, and in Go that can be accomplished by putting a label -on the loop and "breaking" to that label. -This example shows both uses. -

    - -
    -Loop:
    -	for n := 0; n < len(src); n += size {
    -		switch {
    -		case src[n] < sizeOne:
    -			if validateOnly {
    -				break
    -			}
    -			size = 1
    -			update(src[n])
    -
    -		case src[n] < sizeTwo:
    -			if n+1 >= len(src) {
    -				err = errShortInput
    -				break Loop
    -			}
    -			if validateOnly {
    -				break
    -			}
    -			size = 2
    -			update(src[n] + src[n+1]<<shift)
    -		}
    -	}
    -
    - -

    -Of course, the continue statement also accepts an optional label -but it applies only to loops. -

    - -

    -To close this section, here's a comparison routine for byte slices that uses two -switch statements: -

    -
    -// Compare returns an integer comparing the two byte slices,
    -// lexicographically.
    -// The result will be 0 if a == b, -1 if a < b, and +1 if a > b
    -func Compare(a, b []byte) int {
    -    for i := 0; i < len(a) && i < len(b); i++ {
    -        switch {
    -        case a[i] > b[i]:
    -            return 1
    -        case a[i] < b[i]:
    -            return -1
    -        }
    -    }
    -    switch {
    -    case len(a) > len(b):
    -        return 1
    -    case len(a) < len(b):
    -        return -1
    -    }
    -    return 0
    -}
    -
    - -

    Type switch

    - -

    -A switch can also be used to discover the dynamic type of an interface -variable. Such a type switch uses the syntax of a type -assertion with the keyword type inside the parentheses. -If the switch declares a variable in the expression, the variable will -have the corresponding type in each clause. -It's also idiomatic to reuse the name in such cases, in effect declaring -a new variable with the same name but a different type in each case. -

    -
    -var t interface{}
    -t = functionOfSomeType()
    -switch t := t.(type) {
    -default:
    -    fmt.Printf("unexpected type %T\n", t)     // %T prints whatever type t has
    -case bool:
    -    fmt.Printf("boolean %t\n", t)             // t has type bool
    -case int:
    -    fmt.Printf("integer %d\n", t)             // t has type int
    -case *bool:
    -    fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool
    -case *int:
    -    fmt.Printf("pointer to integer %d\n", *t) // t has type *int
    -}
    -
    - -

    Functions

    - -

    Multiple return values

    - -

    -One of Go's unusual features is that functions and methods -can return multiple values. This form can be used to -improve on a couple of clumsy idioms in C programs: in-band -error returns such as -1 for EOF -and modifying an argument passed by address. -

    - -

    -In C, a write error is signaled by a negative count with the -error code secreted away in a volatile location. -In Go, Write -can return a count and an error: “Yes, you wrote some -bytes but not all of them because you filled the device”. -The signature of the Write method on files from -package os is: -

    - -
    -func (file *File) Write(b []byte) (n int, err error)
    -
    - -

    -and as the documentation says, it returns the number of bytes -written and a non-nil error when n -!= len(b). -This is a common style; see the section on error handling for more examples. -

    - -

    -A similar approach obviates the need to pass a pointer to a return -value to simulate a reference parameter. -Here's a simple-minded function to -grab a number from a position in a byte slice, returning the number -and the next position. -

    - -
    -func nextInt(b []byte, i int) (int, int) {
    -    for ; i < len(b) && !isDigit(b[i]); i++ {
    -    }
    -    x := 0
    -    for ; i < len(b) && isDigit(b[i]); i++ {
    -        x = x*10 + int(b[i]) - '0'
    -    }
    -    return x, i
    -}
    -
    - -

    -You could use it to scan the numbers in an input slice b like this: -

    - -
    -    for i := 0; i < len(b); {
    -        x, i = nextInt(b, i)
    -        fmt.Println(x)
    -    }
    -
    - -

    Named result parameters

    - -

    -The return or result "parameters" of a Go function can be given names and -used as regular variables, just like the incoming parameters. -When named, they are initialized to the zero values for their types when -the function begins; if the function executes a return statement -with no arguments, the current values of the result parameters are -used as the returned values. -

    - -

    -The names are not mandatory but they can make code shorter and clearer: -they're documentation. -If we name the results of nextInt it becomes -obvious which returned int -is which. -

    - -
    -func nextInt(b []byte, pos int) (value, nextPos int) {
    -
    - -

    -Because named results are initialized and tied to an unadorned return, they can simplify -as well as clarify. Here's a version -of io.ReadFull that uses them well: -

    - -
    -func ReadFull(r Reader, buf []byte) (n int, err error) {
    -    for len(buf) > 0 && err == nil {
    -        var nr int
    -        nr, err = r.Read(buf)
    -        n += nr
    -        buf = buf[nr:]
    -    }
    -    return
    -}
    -
    - -

    Defer

    - -

    -Go's defer statement schedules a function call (the -deferred function) to be run immediately before the function -executing the defer returns. It's an unusual but -effective way to deal with situations such as resources that must be -released regardless of which path a function takes to return. The -canonical examples are unlocking a mutex or closing a file. -

    - -
    -// Contents returns the file's contents as a string.
    -func Contents(filename string) (string, error) {
    -    f, err := os.Open(filename)
    -    if err != nil {
    -        return "", err
    -    }
    -    defer f.Close()  // f.Close will run when we're finished.
    -
    -    var result []byte
    -    buf := make([]byte, 100)
    -    for {
    -        n, err := f.Read(buf[0:])
    -        result = append(result, buf[0:n]...) // append is discussed later.
    -        if err != nil {
    -            if err == io.EOF {
    -                break
    -            }
    -            return "", err  // f will be closed if we return here.
    -        }
    -    }
    -    return string(result), nil // f will be closed if we return here.
    -}
    -
    - -

    -Deferring a call to a function such as Close has two advantages. First, it -guarantees that you will never forget to close the file, a mistake -that's easy to make if you later edit the function to add a new return -path. Second, it means that the close sits near the open, -which is much clearer than placing it at the end of the function. -

    - -

    -The arguments to the deferred function (which include the receiver if -the function is a method) are evaluated when the defer -executes, not when the call executes. Besides avoiding worries -about variables changing values as the function executes, this means -that a single deferred call site can defer multiple function -executions. Here's a silly example. -

    - -
    -for i := 0; i < 5; i++ {
    -    defer fmt.Printf("%d ", i)
    -}
    -
    - -

    -Deferred functions are executed in LIFO order, so this code will cause -4 3 2 1 0 to be printed when the function returns. A -more plausible example is a simple way to trace function execution -through the program. We could write a couple of simple tracing -routines like this: -

    - -
    -func trace(s string)   { fmt.Println("entering:", s) }
    -func untrace(s string) { fmt.Println("leaving:", s) }
    -
    -// Use them like this:
    -func a() {
    -    trace("a")
    -    defer untrace("a")
    -    // do something....
    -}
    -
    - -

    -We can do better by exploiting the fact that arguments to deferred -functions are evaluated when the defer executes. The -tracing routine can set up the argument to the untracing routine. -This example: -

    - -
    -func trace(s string) string {
    -    fmt.Println("entering:", s)
    -    return s
    -}
    -
    -func un(s string) {
    -    fmt.Println("leaving:", s)
    -}
    -
    -func a() {
    -    defer un(trace("a"))
    -    fmt.Println("in a")
    -}
    -
    -func b() {
    -    defer un(trace("b"))
    -    fmt.Println("in b")
    -    a()
    -}
    -
    -func main() {
    -    b()
    -}
    -
    - -

    -prints -

    - -
    -entering: b
    -in b
    -entering: a
    -in a
    -leaving: a
    -leaving: b
    -
    - -

    -For programmers accustomed to block-level resource management from -other languages, defer may seem peculiar, but its most -interesting and powerful applications come precisely from the fact -that it's not block-based but function-based. In the section on -panic and recover we'll see another -example of its possibilities. -

    - -

    Data

    - -

    Allocation with new

    - -

    -Go has two allocation primitives, the built-in functions -new and make. -They do different things and apply to different types, which can be confusing, -but the rules are simple. -Let's talk about new first. -It's a built-in function that allocates memory, but unlike its namesakes -in some other languages it does not initialize the memory, -it only zeros it. -That is, -new(T) allocates zeroed storage for a new item of type -T and returns its address, a value of type *T. -In Go terminology, it returns a pointer to a newly allocated zero value of type -T. -

    - -

    -Since the memory returned by new is zeroed, it's helpful to arrange -when designing your data structures that the -zero value of each type can be used without further initialization. This means a user of -the data structure can create one with new and get right to -work. -For example, the documentation for bytes.Buffer states that -"the zero value for Buffer is an empty buffer ready to use." -Similarly, sync.Mutex does not -have an explicit constructor or Init method. -Instead, the zero value for a sync.Mutex -is defined to be an unlocked mutex. -

    - -

    -The zero-value-is-useful property works transitively. Consider this type declaration. -

    - -
    -type SyncedBuffer struct {
    -    lock    sync.Mutex
    -    buffer  bytes.Buffer
    -}
    -
    - -

    -Values of type SyncedBuffer are also ready to use immediately upon allocation -or just declaration. In the next snippet, both p and v will work -correctly without further arrangement. -

    - -
    -p := new(SyncedBuffer)  // type *SyncedBuffer
    -var v SyncedBuffer      // type  SyncedBuffer
    -
    - -

    Constructors and composite literals

    - -

    -Sometimes the zero value isn't good enough and an initializing -constructor is necessary, as in this example derived from -package os. -

    - -
    -func NewFile(fd int, name string) *File {
    -    if fd < 0 {
    -        return nil
    -    }
    -    f := new(File)
    -    f.fd = fd
    -    f.name = name
    -    f.dirinfo = nil
    -    f.nepipe = 0
    -    return f
    -}
    -
    - -

    -There's a lot of boiler plate in there. We can simplify it -using a composite literal, which is -an expression that creates a -new instance each time it is evaluated. -

    - -
    -func NewFile(fd int, name string) *File {
    -    if fd < 0 {
    -        return nil
    -    }
    -    f := File{fd, name, nil, 0}
    -    return &f
    -}
    -
    - -

    -Note that, unlike in C, it's perfectly OK to return the address of a local variable; -the storage associated with the variable survives after the function -returns. -In fact, taking the address of a composite literal -allocates a fresh instance each time it is evaluated, -so we can combine these last two lines. -

    - -
    -    return &File{fd, name, nil, 0}
    -
    - -

    -The fields of a composite literal are laid out in order and must all be present. -However, by labeling the elements explicitly as field:value -pairs, the initializers can appear in any -order, with the missing ones left as their respective zero values. Thus we could say -

    - -
    -    return &File{fd: fd, name: name}
    -
    - -

    -As a limiting case, if a composite literal contains no fields at all, it creates -a zero value for the type. The expressions new(File) and &File{} are equivalent. -

    - -

    -Composite literals can also be created for arrays, slices, and maps, -with the field labels being indices or map keys as appropriate. -In these examples, the initializations work regardless of the values of Enone, -Eio, and Einval, as long as they are distinct. -

    - -
    -a := [...]string   {Enone: "no error", Eio: "Eio", Einval: "invalid argument"}
    -s := []string      {Enone: "no error", Eio: "Eio", Einval: "invalid argument"}
    -m := map[int]string{Enone: "no error", Eio: "Eio", Einval: "invalid argument"}
    -
    - -

    Allocation with make

    - -

    -Back to allocation. -The built-in function make(T, args) serves -a purpose different from new(T). -It creates slices, maps, and channels only, and it returns an initialized -(not zeroed) -value of type T (not *T). -The reason for the distinction -is that these three types represent, under the covers, references to data structures that -must be initialized before use. -A slice, for example, is a three-item descriptor -containing a pointer to the data (inside an array), the length, and the -capacity, and until those items are initialized, the slice is nil. -For slices, maps, and channels, -make initializes the internal data structure and prepares -the value for use. -For instance, -

    - -
    -make([]int, 10, 100)
    -
    - -

    -allocates an array of 100 ints and then creates a slice -structure with length 10 and a capacity of 100 pointing at the first -10 elements of the array. -(When making a slice, the capacity can be omitted; see the section on slices -for more information.) -In contrast, new([]int) returns a pointer to a newly allocated, zeroed slice -structure, that is, a pointer to a nil slice value. -

    - -

    -These examples illustrate the difference between new and -make. -

    - -
    -var p *[]int = new([]int)       // allocates slice structure; *p == nil; rarely useful
    -var v  []int = make([]int, 100) // the slice v now refers to a new array of 100 ints
    -
    -// Unnecessarily complex:
    -var p *[]int = new([]int)
    -*p = make([]int, 100, 100)
    -
    -// Idiomatic:
    -v := make([]int, 100)
    -
    - -

    -Remember that make applies only to maps, slices and channels -and does not return a pointer. -To obtain an explicit pointer allocate with new or take the address -of a variable explicitly. -

    - -

    Arrays

    - -

    -Arrays are useful when planning the detailed layout of memory and sometimes -can help avoid allocation, but primarily -they are a building block for slices, the subject of the next section. -To lay the foundation for that topic, here are a few words about arrays. -

    - -

    -There are major differences between the ways arrays work in Go and C. -In Go, -

    -
      -
    • -Arrays are values. Assigning one array to another copies all the elements. -
    • -
    • -In particular, if you pass an array to a function, it -will receive a copy of the array, not a pointer to it. -
    • -The size of an array is part of its type. The types [10]int -and [20]int are distinct. -
    • -
    - -

    -The value property can be useful but also expensive; if you want C-like behavior and efficiency, -you can pass a pointer to the array. -

    - -
    -func Sum(a *[3]float64) (sum float64) {
    -    for _, v := range *a {
    -        sum += v
    -    }
    -    return
    -}
    -
    -array := [...]float64{7.0, 8.5, 9.1}
    -x := Sum(&array)  // Note the explicit address-of operator
    -
    - -

    -But even this style isn't idiomatic Go. -Use slices instead. -

    - -

    Slices

    - -

    -Slices wrap arrays to give a more general, powerful, and convenient -interface to sequences of data. Except for items with explicit -dimension such as transformation matrices, most array programming in -Go is done with slices rather than simple arrays. -

    -

    -Slices hold references to an underlying array, and if you assign one -slice to another, both refer to the same array. -If a function takes a slice argument, changes it makes to -the elements of the slice will be visible to the caller, analogous to -passing a pointer to the underlying array. A Read -function can therefore accept a slice argument rather than a pointer -and a count; the length within the slice sets an upper -limit of how much data to read. Here is the signature of the -Read method of the File type in package -os: -

    -
    -func (f *File) Read(buf []byte) (n int, err error)
    -
    -

    -The method returns the number of bytes read and an error value, if -any. -To read into the first 32 bytes of a larger buffer -buf, slice (here used as a verb) the buffer. -

    -
    -    n, err := f.Read(buf[0:32])
    -
    -

    -Such slicing is common and efficient. In fact, leaving efficiency aside for -the moment, the following snippet would also read the first 32 bytes of the buffer. -

    -
    -    var n int
    -    var err error
    -    for i := 0; i < 32; i++ {
    -        nbytes, e := f.Read(buf[i:i+1])  // Read one byte.
    -        n += nbytes
    -        if nbytes == 0 || e != nil {
    -            err = e
    -            break
    -        }
    -    }
    -
    -

    -The length of a slice may be changed as long as it still fits within -the limits of the underlying array; just assign it to a slice of -itself. The capacity of a slice, accessible by the built-in -function cap, reports the maximum length the slice may -assume. Here is a function to append data to a slice. If the data -exceeds the capacity, the slice is reallocated. The -resulting slice is returned. The function uses the fact that -len and cap are legal when applied to the -nil slice, and return 0. -

    -
    -func Append(slice, data []byte) []byte {
    -    l := len(slice)
    -    if l + len(data) > cap(slice) {  // reallocate
    -        // Allocate double what's needed, for future growth.
    -        newSlice := make([]byte, (l+len(data))*2)
    -        // The copy function is predeclared and works for any slice type.
    -        copy(newSlice, slice)
    -        slice = newSlice
    -    }
    -    slice = slice[0:l+len(data)]
    -    copy(slice[l:], data)
    -    return slice
    -}
    -
    -

    -We must return the slice afterwards because, although Append -can modify the elements of slice, the slice itself (the run-time data -structure holding the pointer, length, and capacity) is passed by value. -

    - -

    -The idea of appending to a slice is so useful it's captured by the -append built-in function. To understand that function's -design, though, we need a little more information, so we'll return -to it later. -

    - -

    Two-dimensional slices

    - -

    -Go's arrays and slices are one-dimensional. -To create the equivalent of a 2D array or slice, it is necessary to define an array-of-arrays -or slice-of-slices, like this: -

    - -
    -type Transform [3][3]float64  // A 3x3 array, really an array of arrays.
    -type LinesOfText [][]byte     // A slice of byte slices.
    -
    - -

    -Because slices are variable-length, it is possible to have each inner -slice be a different length. -That can be a common situation, as in our LinesOfText -example: each line has an independent length. -

    - -
    -text := LinesOfText{
    -	[]byte("Now is the time"),
    -	[]byte("for all good gophers"),
    -	[]byte("to bring some fun to the party."),
    -}
    -
    - -

    -Sometimes it's necessary to allocate a 2D slice, a situation that can arise when -processing scan lines of pixels, for instance. -There are two ways to achieve this. -One is to allocate each slice independently; the other -is to allocate a single array and point the individual slices into it. -Which to use depends on your application. -If the slices might grow or shrink, they should be allocated independently -to avoid overwriting the next line; if not, it can be more efficient to construct -the object with a single allocation. -For reference, here are sketches of the two methods. -First, a line at a time: -

    - -
    -// Allocate the top-level slice.
    -picture := make([][]uint8, YSize) // One row per unit of y.
    -// Loop over the rows, allocating the slice for each row.
    -for i := range picture {
    -	picture[i] = make([]uint8, XSize)
    -}
    -
    - -

    -And now as one allocation, sliced into lines: -

    - -
    -// Allocate the top-level slice, the same as before.
    -picture := make([][]uint8, YSize) // One row per unit of y.
    -// Allocate one large slice to hold all the pixels.
    -pixels := make([]uint8, XSize*YSize) // Has type []uint8 even though picture is [][]uint8.
    -// Loop over the rows, slicing each row from the front of the remaining pixels slice.
    -for i := range picture {
    -	picture[i], pixels = pixels[:XSize], pixels[XSize:]
    -}
    -
    - -

    Maps

    - -

    -Maps are a convenient and powerful built-in data structure that associate -values of one type (the key) with values of another type -(the element or value). -The key can be of any type for which the equality operator is defined, -such as integers, -floating point and complex numbers, -strings, pointers, interfaces (as long as the dynamic type -supports equality), structs and arrays. -Slices cannot be used as map keys, -because equality is not defined on them. -Like slices, maps hold references to an underlying data structure. -If you pass a map to a function -that changes the contents of the map, the changes will be visible -in the caller. -

    -

    -Maps can be constructed using the usual composite literal syntax -with colon-separated key-value pairs, -so it's easy to build them during initialization. -

    -
    -var timeZone = map[string]int{
    -    "UTC":  0*60*60,
    -    "EST": -5*60*60,
    -    "CST": -6*60*60,
    -    "MST": -7*60*60,
    -    "PST": -8*60*60,
    -}
    -
    -

    -Assigning and fetching map values looks syntactically just like -doing the same for arrays and slices except that the index doesn't -need to be an integer. -

    -
    -offset := timeZone["EST"]
    -
    -

    -An attempt to fetch a map value with a key that -is not present in the map will return the zero value for the type -of the entries -in the map. For instance, if the map contains integers, looking -up a non-existent key will return 0. -A set can be implemented as a map with value type bool. -Set the map entry to true to put the value in the set, and then -test it by simple indexing. -

    -
    -attended := map[string]bool{
    -    "Ann": true,
    -    "Joe": true,
    -    ...
    -}
    -
    -if attended[person] { // will be false if person is not in the map
    -    fmt.Println(person, "was at the meeting")
    -}
    -
    -

    -Sometimes you need to distinguish a missing entry from -a zero value. Is there an entry for "UTC" -or is that 0 because it's not in the map at all? -You can discriminate with a form of multiple assignment. -

    -
    -var seconds int
    -var ok bool
    -seconds, ok = timeZone[tz]
    -
    -

    -For obvious reasons this is called the “comma ok” idiom. -In this example, if tz is present, seconds -will be set appropriately and ok will be true; if not, -seconds will be set to zero and ok will -be false. -Here's a function that puts it together with a nice error report: -

    -
    -func offset(tz string) int {
    -    if seconds, ok := timeZone[tz]; ok {
    -        return seconds
    -    }
    -    log.Println("unknown time zone:", tz)
    -    return 0
    -}
    -
    -

    -To test for presence in the map without worrying about the actual value, -you can use the blank identifier (_) -in place of the usual variable for the value. -

    -
    -_, present := timeZone[tz]
    -
    -

    -To delete a map entry, use the delete -built-in function, whose arguments are the map and the key to be deleted. -It's safe to do this even if the key is already absent -from the map. -

    -
    -delete(timeZone, "PDT")  // Now on Standard Time
    -
    - -

    Printing

    - -

    -Formatted printing in Go uses a style similar to C's printf -family but is richer and more general. The functions live in the fmt -package and have capitalized names: fmt.Printf, fmt.Fprintf, -fmt.Sprintf and so on. The string functions (Sprintf etc.) -return a string rather than filling in a provided buffer. -

    -

    -You don't need to provide a format string. For each of Printf, -Fprintf and Sprintf there is another pair -of functions, for instance Print and Println. -These functions do not take a format string but instead generate a default -format for each argument. The Println versions also insert a blank -between arguments and append a newline to the output while -the Print versions add blanks only if the operand on neither side is a string. -In this example each line produces the same output. -

    -
    -fmt.Printf("Hello %d\n", 23)
    -fmt.Fprint(os.Stdout, "Hello ", 23, "\n")
    -fmt.Println("Hello", 23)
    -fmt.Println(fmt.Sprint("Hello ", 23))
    -
    -

    -The formatted print functions fmt.Fprint -and friends take as a first argument any object -that implements the io.Writer interface; the variables os.Stdout -and os.Stderr are familiar instances. -

    -

    -Here things start to diverge from C. First, the numeric formats such as %d -do not take flags for signedness or size; instead, the printing routines use the -type of the argument to decide these properties. -

    -
    -var x uint64 = 1<<64 - 1
    -fmt.Printf("%d %x; %d %x\n", x, x, int64(x), int64(x))
    -
    -

    -prints -

    -
    -18446744073709551615 ffffffffffffffff; -1 -1
    -
    -

    -If you just want the default conversion, such as decimal for integers, you can use -the catchall format %v (for “value”); the result is exactly -what Print and Println would produce. -Moreover, that format can print any value, even arrays, slices, structs, and -maps. Here is a print statement for the time zone map defined in the previous section. -

    -
    -fmt.Printf("%v\n", timeZone)  // or just fmt.Println(timeZone)
    -
    -

    -which gives output: -

    -
    -map[CST:-21600 EST:-18000 MST:-25200 PST:-28800 UTC:0]
    -
    -

    -For maps, Printf and friends sort the output lexicographically by key. -

    -

    -When printing a struct, the modified format %+v annotates the -fields of the structure with their names, and for any value the alternate -format %#v prints the value in full Go syntax. -

    -
    -type T struct {
    -    a int
    -    b float64
    -    c string
    -}
    -t := &T{ 7, -2.35, "abc\tdef" }
    -fmt.Printf("%v\n", t)
    -fmt.Printf("%+v\n", t)
    -fmt.Printf("%#v\n", t)
    -fmt.Printf("%#v\n", timeZone)
    -
    -

    -prints -

    -
    -&{7 -2.35 abc   def}
    -&{a:7 b:-2.35 c:abc     def}
    -&main.T{a:7, b:-2.35, c:"abc\tdef"}
    -map[string]int{"CST":-21600, "EST":-18000, "MST":-25200, "PST":-28800, "UTC":0}
    -
    -

    -(Note the ampersands.) -That quoted string format is also available through %q when -applied to a value of type string or []byte. -The alternate format %#q will use backquotes instead if possible. -(The %q format also applies to integers and runes, producing a -single-quoted rune constant.) -Also, %x works on strings, byte arrays and byte slices as well as -on integers, generating a long hexadecimal string, and with -a space in the format (% x) it puts spaces between the bytes. -

    -

    -Another handy format is %T, which prints the type of a value. -

    -
    -fmt.Printf("%T\n", timeZone)
    -
    -

    -prints -

    -
    -map[string]int
    -
    -

    -If you want to control the default format for a custom type, all that's required is to define -a method with the signature String() string on the type. -For our simple type T, that might look like this. -

    -
    -func (t *T) String() string {
    -    return fmt.Sprintf("%d/%g/%q", t.a, t.b, t.c)
    -}
    -fmt.Printf("%v\n", t)
    -
    -

    -to print in the format -

    -
    -7/-2.35/"abc\tdef"
    -
    -

    -(If you need to print values of type T as well as pointers to T, -the receiver for String must be of value type; this example used a pointer because -that's more efficient and idiomatic for struct types. -See the section below on pointers vs. value receivers for more information.) -

    - -

    -Our String method is able to call Sprintf because the -print routines are fully reentrant and can be wrapped this way. -There is one important detail to understand about this approach, -however: don't construct a String method by calling -Sprintf in a way that will recur into your String -method indefinitely. This can happen if the Sprintf -call attempts to print the receiver directly as a string, which in -turn will invoke the method again. It's a common and easy mistake -to make, as this example shows. -

    - -
    -type MyString string
    -
    -func (m MyString) String() string {
    -    return fmt.Sprintf("MyString=%s", m) // Error: will recur forever.
    -}
    -
    - -

    -It's also easy to fix: convert the argument to the basic string type, which does not have the -method. -

    - -
    -type MyString string
    -func (m MyString) String() string {
    -    return fmt.Sprintf("MyString=%s", string(m)) // OK: note conversion.
    -}
    -
    - -

    -In the initialization section we'll see another technique that avoids this recursion. -

    - -

    -Another printing technique is to pass a print routine's arguments directly to another such routine. -The signature of Printf uses the type ...interface{} -for its final argument to specify that an arbitrary number of parameters (of arbitrary type) -can appear after the format. -

    -
    -func Printf(format string, v ...interface{}) (n int, err error) {
    -
    -

    -Within the function Printf, v acts like a variable of type -[]interface{} but if it is passed to another variadic function, it acts like -a regular list of arguments. -Here is the implementation of the -function log.Println we used above. It passes its arguments directly to -fmt.Sprintln for the actual formatting. -

    -
    -// Println prints to the standard logger in the manner of fmt.Println.
    -func Println(v ...interface{}) {
    -    std.Output(2, fmt.Sprintln(v...))  // Output takes parameters (int, string)
    -}
    -
    -

    -We write ... after v in the nested call to Sprintln to tell the -compiler to treat v as a list of arguments; otherwise it would just pass -v as a single slice argument. -

    -

    -There's even more to printing than we've covered here. See the godoc documentation -for package fmt for the details. -

    -

    -By the way, a ... parameter can be of a specific type, for instance ...int -for a min function that chooses the least of a list of integers: -

    -
    -func Min(a ...int) int {
    -    min := int(^uint(0) >> 1)  // largest int
    -    for _, i := range a {
    -        if i < min {
    -            min = i
    -        }
    -    }
    -    return min
    -}
    -
    - -

    Append

    -

    -Now we have the missing piece we needed to explain the design of -the append built-in function. The signature of append -is different from our custom Append function above. -Schematically, it's like this: -

    -
    -func append(slice []T, elements ...T) []T
    -
    -

    -where T is a placeholder for any given type. You can't -actually write a function in Go where the type T -is determined by the caller. -That's why append is built in: it needs support from the -compiler. -

    -

    -What append does is append the elements to the end of -the slice and return the result. The result needs to be returned -because, as with our hand-written Append, the underlying -array may change. This simple example -

    -
    -x := []int{1,2,3}
    -x = append(x, 4, 5, 6)
    -fmt.Println(x)
    -
    -

    -prints [1 2 3 4 5 6]. So append works a -little like Printf, collecting an arbitrary number of -arguments. -

    -

    -But what if we wanted to do what our Append does and -append a slice to a slice? Easy: use ... at the call -site, just as we did in the call to Output above. This -snippet produces identical output to the one above. -

    -
    -x := []int{1,2,3}
    -y := []int{4,5,6}
    -x = append(x, y...)
    -fmt.Println(x)
    -
    -

    -Without that ..., it wouldn't compile because the types -would be wrong; y is not of type int. -

    - -

    Initialization

    - -

    -Although it doesn't look superficially very different from -initialization in C or C++, initialization in Go is more powerful. -Complex structures can be built during initialization and the ordering -issues among initialized objects, even among different packages, are handled -correctly. -

    - -

    Constants

    - -

    -Constants in Go are just that—constant. -They are created at compile time, even when defined as -locals in functions, -and can only be numbers, characters (runes), strings or booleans. -Because of the compile-time restriction, the expressions -that define them must be constant expressions, -evaluatable by the compiler. For instance, -1<<3 is a constant expression, while -math.Sin(math.Pi/4) is not because -the function call to math.Sin needs -to happen at run time. -

    - -

    -In Go, enumerated constants are created using the iota -enumerator. Since iota can be part of an expression and -expressions can be implicitly repeated, it is easy to build intricate -sets of values. -

    -{{code "/doc/progs/eff_bytesize.go" `/^type ByteSize/` `/^\)/`}} -

    -The ability to attach a method such as String to any -user-defined type makes it possible for arbitrary values to format themselves -automatically for printing. -Although you'll see it most often applied to structs, this technique is also useful for -scalar types such as floating-point types like ByteSize. -

    -{{code "/doc/progs/eff_bytesize.go" `/^func.*ByteSize.*String/` `/^}/`}} -

    -The expression YB prints as 1.00YB, -while ByteSize(1e13) prints as 9.09TB. -

    - -

    -The use here of Sprintf -to implement ByteSize's String method is safe -(avoids recurring indefinitely) not because of a conversion but -because it calls Sprintf with %f, -which is not a string format: Sprintf will only call -the String method when it wants a string, and %f -wants a floating-point value. -

    - -

    Variables

    - -

    -Variables can be initialized just like constants but the -initializer can be a general expression computed at run time. -

    -
    -var (
    -    home   = os.Getenv("HOME")
    -    user   = os.Getenv("USER")
    -    gopath = os.Getenv("GOPATH")
    -)
    -
    - -

    The init function

    - -

    -Finally, each source file can define its own niladic init function to -set up whatever state is required. (Actually each file can have multiple -init functions.) -And finally means finally: init is called after all the -variable declarations in the package have evaluated their initializers, -and those are evaluated only after all the imported packages have been -initialized. -

    -

    -Besides initializations that cannot be expressed as declarations, -a common use of init functions is to verify or repair -correctness of the program state before real execution begins. -

    - -
    -func init() {
    -    if user == "" {
    -        log.Fatal("$USER not set")
    -    }
    -    if home == "" {
    -        home = "/home/" + user
    -    }
    -    if gopath == "" {
    -        gopath = home + "/go"
    -    }
    -    // gopath may be overridden by --gopath flag on command line.
    -    flag.StringVar(&gopath, "gopath", gopath, "override default GOPATH")
    -}
    -
    - -

    Methods

    - -

    Pointers vs. Values

    -

    -As we saw with ByteSize, -methods can be defined for any named type (except a pointer or an interface); -the receiver does not have to be a struct. -

    -

    -In the discussion of slices above, we wrote an Append -function. We can define it as a method on slices instead. To do -this, we first declare a named type to which we can bind the method, and -then make the receiver for the method a value of that type. -

    -
    -type ByteSlice []byte
    -
    -func (slice ByteSlice) Append(data []byte) []byte {
    -    // Body exactly the same as the Append function defined above.
    -}
    -
    -

    -This still requires the method to return the updated slice. We can -eliminate that clumsiness by redefining the method to take a -pointer to a ByteSlice as its receiver, so the -method can overwrite the caller's slice. -

    -
    -func (p *ByteSlice) Append(data []byte) {
    -    slice := *p
    -    // Body as above, without the return.
    -    *p = slice
    -}
    -
    -

    -In fact, we can do even better. If we modify our function so it looks -like a standard Write method, like this, -

    -
    -func (p *ByteSlice) Write(data []byte) (n int, err error) {
    -    slice := *p
    -    // Again as above.
    -    *p = slice
    -    return len(data), nil
    -}
    -
    -

    -then the type *ByteSlice satisfies the standard interface -io.Writer, which is handy. For instance, we can -print into one. -

    -
    -    var b ByteSlice
    -    fmt.Fprintf(&b, "This hour has %d days\n", 7)
    -
    -

    -We pass the address of a ByteSlice -because only *ByteSlice satisfies io.Writer. -The rule about pointers vs. values for receivers is that value methods -can be invoked on pointers and values, but pointer methods can only be -invoked on pointers. -

    - -

    -This rule arises because pointer methods can modify the receiver; invoking -them on a value would cause the method to receive a copy of the value, so -any modifications would be discarded. -The language therefore disallows this mistake. -There is a handy exception, though. When the value is addressable, the -language takes care of the common case of invoking a pointer method on a -value by inserting the address operator automatically. -In our example, the variable b is addressable, so we can call -its Write method with just b.Write. The compiler -will rewrite that to (&b).Write for us. -

    - -

    -By the way, the idea of using Write on a slice of bytes -is central to the implementation of bytes.Buffer. -

    - -

    Interfaces and other types

    - -

    Interfaces

    -

    -Interfaces in Go provide a way to specify the behavior of an -object: if something can do this, then it can be used -here. We've seen a couple of simple examples already; -custom printers can be implemented by a String method -while Fprintf can generate output to anything -with a Write method. -Interfaces with only one or two methods are common in Go code, and are -usually given a name derived from the method, such as io.Writer -for something that implements Write. -

    -

    -A type can implement multiple interfaces. -For instance, a collection can be sorted -by the routines in package sort if it implements -sort.Interface, which contains Len(), -Less(i, j int) bool, and Swap(i, j int), -and it could also have a custom formatter. -In this contrived example Sequence satisfies both. -

    -{{code "/doc/progs/eff_sequence.go" `/^type/` "$"}} - -

    Conversions

    - -

    -The String method of Sequence is recreating the -work that Sprint already does for slices. -(It also has complexity O(N²), which is poor.) We can share the -effort (and also speed it up) if we convert the Sequence to a plain -[]int before calling Sprint. -

    -
    -func (s Sequence) String() string {
    -    s = s.Copy()
    -    sort.Sort(s)
    -    return fmt.Sprint([]int(s))
    -}
    -
    -

    -This method is another example of the conversion technique for calling -Sprintf safely from a String method. -Because the two types (Sequence and []int) -are the same if we ignore the type name, it's legal to convert between them. -The conversion doesn't create a new value, it just temporarily acts -as though the existing value has a new type. -(There are other legal conversions, such as from integer to floating point, that -do create a new value.) -

    -

    -It's an idiom in Go programs to convert the -type of an expression to access a different -set of methods. As an example, we could use the existing -type sort.IntSlice to reduce the entire example -to this: -

    -
    -type Sequence []int
    -
    -// Method for printing - sorts the elements before printing
    -func (s Sequence) String() string {
    -    s = s.Copy()
    -    sort.IntSlice(s).Sort()
    -    return fmt.Sprint([]int(s))
    -}
    -
    -

    -Now, instead of having Sequence implement multiple -interfaces (sorting and printing), we're using the ability of a data item to be -converted to multiple types (Sequence, sort.IntSlice -and []int), each of which does some part of the job. -That's more unusual in practice but can be effective. -

    - -

    Interface conversions and type assertions

    - -

    -Type switches are a form of conversion: they take an interface and, for -each case in the switch, in a sense convert it to the type of that case. -Here's a simplified version of how the code under fmt.Printf turns a value into -a string using a type switch. -If it's already a string, we want the actual string value held by the interface, while if it has a -String method we want the result of calling the method. -

    - -
    -type Stringer interface {
    -    String() string
    -}
    -
    -var value interface{} // Value provided by caller.
    -switch str := value.(type) {
    -case string:
    -    return str
    -case Stringer:
    -    return str.String()
    -}
    -
    - -

    -The first case finds a concrete value; the second converts the interface into another interface. -It's perfectly fine to mix types this way. -

    - -

    -What if there's only one type we care about? If we know the value holds a string -and we just want to extract it? -A one-case type switch would do, but so would a type assertion. -A type assertion takes an interface value and extracts from it a value of the specified explicit type. -The syntax borrows from the clause opening a type switch, but with an explicit -type rather than the type keyword: -

    - -
    -value.(typeName)
    -
    - -

    -and the result is a new value with the static type typeName. -That type must either be the concrete type held by the interface, or a second interface -type that the value can be converted to. -To extract the string we know is in the value, we could write: -

    - -
    -str := value.(string)
    -
    - -

    -But if it turns out that the value does not contain a string, the program will crash with a run-time error. -To guard against that, use the "comma, ok" idiom to test, safely, whether the value is a string: -

    - -
    -str, ok := value.(string)
    -if ok {
    -    fmt.Printf("string value is: %q\n", str)
    -} else {
    -    fmt.Printf("value is not a string\n")
    -}
    -
    - -

    -If the type assertion fails, str will still exist and be of type string, but it will have -the zero value, an empty string. -

    - -

    -As an illustration of the capability, here's an if-else -statement that's equivalent to the type switch that opened this section. -

    - -
    -if str, ok := value.(string); ok {
    -    return str
    -} else if str, ok := value.(Stringer); ok {
    -    return str.String()
    -}
    -
    - -

    Generality

    -

    -If a type exists only to implement an interface and will -never have exported methods beyond that interface, there is -no need to export the type itself. -Exporting just the interface makes it clear the value has no -interesting behavior beyond what is described in the -interface. -It also avoids the need to repeat the documentation -on every instance of a common method. -

    -

    -In such cases, the constructor should return an interface value -rather than the implementing type. -As an example, in the hash libraries -both crc32.NewIEEE and adler32.New -return the interface type hash.Hash32. -Substituting the CRC-32 algorithm for Adler-32 in a Go program -requires only changing the constructor call; -the rest of the code is unaffected by the change of algorithm. -

    -

    -A similar approach allows the streaming cipher algorithms -in the various crypto packages to be -separated from the block ciphers they chain together. -The Block interface -in the crypto/cipher package specifies the -behavior of a block cipher, which provides encryption -of a single block of data. -Then, by analogy with the bufio package, -cipher packages that implement this interface -can be used to construct streaming ciphers, represented -by the Stream interface, without -knowing the details of the block encryption. -

    -

    -The crypto/cipher interfaces look like this: -

    -
    -type Block interface {
    -    BlockSize() int
    -    Encrypt(dst, src []byte)
    -    Decrypt(dst, src []byte)
    -}
    -
    -type Stream interface {
    -    XORKeyStream(dst, src []byte)
    -}
    -
    - -

    -Here's the definition of the counter mode (CTR) stream, -which turns a block cipher into a streaming cipher; notice -that the block cipher's details are abstracted away: -

    - -
    -// NewCTR returns a Stream that encrypts/decrypts using the given Block in
    -// counter mode. The length of iv must be the same as the Block's block size.
    -func NewCTR(block Block, iv []byte) Stream
    -
    -

    -NewCTR applies not -just to one specific encryption algorithm and data source but to any -implementation of the Block interface and any -Stream. Because they return -interface values, replacing CTR -encryption with other encryption modes is a localized change. The constructor -calls must be edited, but because the surrounding code must treat the result only -as a Stream, it won't notice the difference. -

    - -

    Interfaces and methods

    -

    -Since almost anything can have methods attached, almost anything can -satisfy an interface. One illustrative example is in the http -package, which defines the Handler interface. Any object -that implements Handler can serve HTTP requests. -

    -
    -type Handler interface {
    -    ServeHTTP(ResponseWriter, *Request)
    -}
    -
    -

    -ResponseWriter is itself an interface that provides access -to the methods needed to return the response to the client. -Those methods include the standard Write method, so an -http.ResponseWriter can be used wherever an io.Writer -can be used. -Request is a struct containing a parsed representation -of the request from the client. -

    -

    -For brevity, let's ignore POSTs and assume HTTP requests are always -GETs; that simplification does not affect the way the handlers are set up. -Here's a trivial implementation of a handler to count the number of times -the page is visited. -

    -
    -// Simple counter server.
    -type Counter struct {
    -    n int
    -}
    -
    -func (ctr *Counter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    -    ctr.n++
    -    fmt.Fprintf(w, "counter = %d\n", ctr.n)
    -}
    -
    -

    -(Keeping with our theme, note how Fprintf can print to an -http.ResponseWriter.) -In a real server, access to ctr.n would need protection from -concurrent access. -See the sync and atomic packages for suggestions. -

    -

    -For reference, here's how to attach such a server to a node on the URL tree. -

    -
    -import "net/http"
    -...
    -ctr := new(Counter)
    -http.Handle("/counter", ctr)
    -
    -

    -But why make Counter a struct? An integer is all that's needed. -(The receiver needs to be a pointer so the increment is visible to the caller.) -

    -
    -// Simpler counter server.
    -type Counter int
    -
    -func (ctr *Counter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    -    *ctr++
    -    fmt.Fprintf(w, "counter = %d\n", *ctr)
    -}
    -
    -

    -What if your program has some internal state that needs to be notified that a page -has been visited? Tie a channel to the web page. -

    -
    -// A channel that sends a notification on each visit.
    -// (Probably want the channel to be buffered.)
    -type Chan chan *http.Request
    -
    -func (ch Chan) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    -    ch <- req
    -    fmt.Fprint(w, "notification sent")
    -}
    -
    -

    -Finally, let's say we wanted to present on /args the arguments -used when invoking the server binary. -It's easy to write a function to print the arguments. -

    -
    -func ArgServer() {
    -    fmt.Println(os.Args)
    -}
    -
    -

    -How do we turn that into an HTTP server? We could make ArgServer -a method of some type whose value we ignore, but there's a cleaner way. -Since we can define a method for any type except pointers and interfaces, -we can write a method for a function. -The http package contains this code: -

    -
    -// The HandlerFunc type is an adapter to allow the use of
    -// ordinary functions as HTTP handlers.  If f is a function
    -// with the appropriate signature, HandlerFunc(f) is a
    -// Handler object that calls f.
    -type HandlerFunc func(ResponseWriter, *Request)
    -
    -// ServeHTTP calls f(w, req).
    -func (f HandlerFunc) ServeHTTP(w ResponseWriter, req *Request) {
    -    f(w, req)
    -}
    -
    -

    -HandlerFunc is a type with a method, ServeHTTP, -so values of that type can serve HTTP requests. Look at the implementation -of the method: the receiver is a function, f, and the method -calls f. That may seem odd but it's not that different from, say, -the receiver being a channel and the method sending on the channel. -

    -

    -To make ArgServer into an HTTP server, we first modify it -to have the right signature. -

    -
    -// Argument server.
    -func ArgServer(w http.ResponseWriter, req *http.Request) {
    -    fmt.Fprintln(w, os.Args)
    -}
    -
    -

    -ArgServer now has same signature as HandlerFunc, -so it can be converted to that type to access its methods, -just as we converted Sequence to IntSlice -to access IntSlice.Sort. -The code to set it up is concise: -

    -
    -http.Handle("/args", http.HandlerFunc(ArgServer))
    -
    -

    -When someone visits the page /args, -the handler installed at that page has value ArgServer -and type HandlerFunc. -The HTTP server will invoke the method ServeHTTP -of that type, with ArgServer as the receiver, which will in turn call -ArgServer (via the invocation f(w, req) -inside HandlerFunc.ServeHTTP). -The arguments will then be displayed. -

    -

    -In this section we have made an HTTP server from a struct, an integer, -a channel, and a function, all because interfaces are just sets of -methods, which can be defined for (almost) any type. -

    - -

    The blank identifier

    - -

    -We've mentioned the blank identifier a couple of times now, in the context of -for range loops -and maps. -The blank identifier can be assigned or declared with any value of any type, with the -value discarded harmlessly. -It's a bit like writing to the Unix /dev/null file: -it represents a write-only value -to be used as a place-holder -where a variable is needed but the actual value is irrelevant. -It has uses beyond those we've seen already. -

    - -

    The blank identifier in multiple assignment

    - -

    -The use of a blank identifier in a for range loop is a -special case of a general situation: multiple assignment. -

    - -

    -If an assignment requires multiple values on the left side, -but one of the values will not be used by the program, -a blank identifier on the left-hand-side of -the assignment avoids the need -to create a dummy variable and makes it clear that the -value is to be discarded. -For instance, when calling a function that returns -a value and an error, but only the error is important, -use the blank identifier to discard the irrelevant value. -

    - -
    -if _, err := os.Stat(path); os.IsNotExist(err) {
    -	fmt.Printf("%s does not exist\n", path)
    -}
    -
    - -

    -Occasionally you'll see code that discards the error value in order -to ignore the error; this is terrible practice. Always check error returns; -they're provided for a reason. -

    - -
    -// Bad! This code will crash if path does not exist.
    -fi, _ := os.Stat(path)
    -if fi.IsDir() {
    -    fmt.Printf("%s is a directory\n", path)
    -}
    -
    - -

    Unused imports and variables

    - -

    -It is an error to import a package or to declare a variable without using it. -Unused imports bloat the program and slow compilation, -while a variable that is initialized but not used is at least -a wasted computation and perhaps indicative of a -larger bug. -When a program is under active development, however, -unused imports and variables often arise and it can -be annoying to delete them just to have the compilation proceed, -only to have them be needed again later. -The blank identifier provides a workaround. -

    -

    -This half-written program has two unused imports -(fmt and io) -and an unused variable (fd), -so it will not compile, but it would be nice to see if the -code so far is correct. -

    -{{code "/doc/progs/eff_unused1.go" `/package/` `$`}} -

    -To silence complaints about the unused imports, use a -blank identifier to refer to a symbol from the imported package. -Similarly, assigning the unused variable fd -to the blank identifier will silence the unused variable error. -This version of the program does compile. -

    -{{code "/doc/progs/eff_unused2.go" `/package/` `$`}} - -

    -By convention, the global declarations to silence import errors -should come right after the imports and be commented, -both to make them easy to find and as a reminder to clean things up later. -

    - -

    Import for side effect

    - -

    -An unused import like fmt or io in the -previous example should eventually be used or removed: -blank assignments identify code as a work in progress. -But sometimes it is useful to import a package only for its -side effects, without any explicit use. -For example, during its init function, -the net/http/pprof -package registers HTTP handlers that provide -debugging information. It has an exported API, but -most clients need only the handler registration and -access the data through a web page. -To import the package only for its side effects, rename the package -to the blank identifier: -

    -
    -import _ "net/http/pprof"
    -
    -

    -This form of import makes clear that the package is being -imported for its side effects, because there is no other possible -use of the package: in this file, it doesn't have a name. -(If it did, and we didn't use that name, the compiler would reject the program.) -

    - -

    Interface checks

    - -

    -As we saw in the discussion of interfaces above, -a type need not declare explicitly that it implements an interface. -Instead, a type implements the interface just by implementing the interface's methods. -In practice, most interface conversions are static and therefore checked at compile time. -For example, passing an *os.File to a function -expecting an io.Reader will not compile unless -*os.File implements the io.Reader interface. -

    - -

    -Some interface checks do happen at run-time, though. -One instance is in the encoding/json -package, which defines a Marshaler -interface. When the JSON encoder receives a value that implements that interface, -the encoder invokes the value's marshaling method to convert it to JSON -instead of doing the standard conversion. -The encoder checks this property at run time with a type assertion like: -

    - -
    -m, ok := val.(json.Marshaler)
    -
    - -

    -If it's necessary only to ask whether a type implements an interface, without -actually using the interface itself, perhaps as part of an error check, use the blank -identifier to ignore the type-asserted value: -

    - -
    -if _, ok := val.(json.Marshaler); ok {
    -    fmt.Printf("value %v of type %T implements json.Marshaler\n", val, val)
    -}
    -
    - -

    -One place this situation arises is when it is necessary to guarantee within the package implementing the type that -it actually satisfies the interface. -If a type—for example, -json.RawMessage—needs -a custom JSON representation, it should implement -json.Marshaler, but there are no static conversions that would -cause the compiler to verify this automatically. -If the type inadvertently fails to satisfy the interface, the JSON encoder will still work, -but will not use the custom implementation. -To guarantee that the implementation is correct, -a global declaration using the blank identifier can be used in the package: -

    -
    -var _ json.Marshaler = (*RawMessage)(nil)
    -
    -

    -In this declaration, the assignment involving a conversion of a -*RawMessage to a Marshaler -requires that *RawMessage implements Marshaler, -and that property will be checked at compile time. -Should the json.Marshaler interface change, this package -will no longer compile and we will be on notice that it needs to be updated. -

    - -

    -The appearance of the blank identifier in this construct indicates that -the declaration exists only for the type checking, -not to create a variable. -Don't do this for every type that satisfies an interface, though. -By convention, such declarations are only used -when there are no static conversions already present in the code, -which is a rare event. -

    - - -

    Embedding

    - -

    -Go does not provide the typical, type-driven notion of subclassing, -but it does have the ability to “borrow” pieces of an -implementation by embedding types within a struct or -interface. -

    -

    -Interface embedding is very simple. -We've mentioned the io.Reader and io.Writer interfaces before; -here are their definitions. -

    -
    -type Reader interface {
    -    Read(p []byte) (n int, err error)
    -}
    -
    -type Writer interface {
    -    Write(p []byte) (n int, err error)
    -}
    -
    -

    -The io package also exports several other interfaces -that specify objects that can implement several such methods. -For instance, there is io.ReadWriter, an interface -containing both Read and Write. -We could specify io.ReadWriter by listing the -two methods explicitly, but it's easier and more evocative -to embed the two interfaces to form the new one, like this: -

    -
    -// ReadWriter is the interface that combines the Reader and Writer interfaces.
    -type ReadWriter interface {
    -    Reader
    -    Writer
    -}
    -
    -

    -This says just what it looks like: A ReadWriter can do -what a Reader does and what a Writer -does; it is a union of the embedded interfaces. -Only interfaces can be embedded within interfaces. -

    -

    -The same basic idea applies to structs, but with more far-reaching -implications. The bufio package has two struct types, -bufio.Reader and bufio.Writer, each of -which of course implements the analogous interfaces from package -io. -And bufio also implements a buffered reader/writer, -which it does by combining a reader and a writer into one struct -using embedding: it lists the types within the struct -but does not give them field names. -

    -
    -// ReadWriter stores pointers to a Reader and a Writer.
    -// It implements io.ReadWriter.
    -type ReadWriter struct {
    -    *Reader  // *bufio.Reader
    -    *Writer  // *bufio.Writer
    -}
    -
    -

    -The embedded elements are pointers to structs and of course -must be initialized to point to valid structs before they -can be used. -The ReadWriter struct could be written as -

    -
    -type ReadWriter struct {
    -    reader *Reader
    -    writer *Writer
    -}
    -
    -

    -but then to promote the methods of the fields and to -satisfy the io interfaces, we would also need -to provide forwarding methods, like this: -

    -
    -func (rw *ReadWriter) Read(p []byte) (n int, err error) {
    -    return rw.reader.Read(p)
    -}
    -
    -

    -By embedding the structs directly, we avoid this bookkeeping. -The methods of embedded types come along for free, which means that bufio.ReadWriter -not only has the methods of bufio.Reader and bufio.Writer, -it also satisfies all three interfaces: -io.Reader, -io.Writer, and -io.ReadWriter. -

    -

    -There's an important way in which embedding differs from subclassing. When we embed a type, -the methods of that type become methods of the outer type, -but when they are invoked the receiver of the method is the inner type, not the outer one. -In our example, when the Read method of a bufio.ReadWriter is -invoked, it has exactly the same effect as the forwarding method written out above; -the receiver is the reader field of the ReadWriter, not the -ReadWriter itself. -

    -

    -Embedding can also be a simple convenience. -This example shows an embedded field alongside a regular, named field. -

    -
    -type Job struct {
    -    Command string
    -    *log.Logger
    -}
    -
    -

    -The Job type now has the Print, Printf, Println -and other -methods of *log.Logger. We could have given the Logger -a field name, of course, but it's not necessary to do so. And now, once -initialized, we can -log to the Job: -

    -
    -job.Println("starting now...")
    -
    -

    -The Logger is a regular field of the Job struct, -so we can initialize it in the usual way inside the constructor for Job, like this, -

    -
    -func NewJob(command string, logger *log.Logger) *Job {
    -    return &Job{command, logger}
    -}
    -
    -

    -or with a composite literal, -

    -
    -job := &Job{command, log.New(os.Stderr, "Job: ", log.Ldate)}
    -
    -

    -If we need to refer to an embedded field directly, the type name of the field, -ignoring the package qualifier, serves as a field name, as it did -in the Read method of our ReadWriter struct. -Here, if we needed to access the -*log.Logger of a Job variable job, -we would write job.Logger, -which would be useful if we wanted to refine the methods of Logger. -

    -
    -func (job *Job) Printf(format string, args ...interface{}) {
    -    job.Logger.Printf("%q: %s", job.Command, fmt.Sprintf(format, args...))
    -}
    -
    -

    -Embedding types introduces the problem of name conflicts but the rules to resolve -them are simple. -First, a field or method X hides any other item X in a more deeply -nested part of the type. -If log.Logger contained a field or method called Command, the Command field -of Job would dominate it. -

    -

    -Second, if the same name appears at the same nesting level, it is usually an error; -it would be erroneous to embed log.Logger if the Job struct -contained another field or method called Logger. -However, if the duplicate name is never mentioned in the program outside the type definition, it is OK. -This qualification provides some protection against changes made to types embedded from outside; there -is no problem if a field is added that conflicts with another field in another subtype if neither field -is ever used. -

    - - -

    Concurrency

    - -

    Share by communicating

    - -

    -Concurrent programming is a large topic and there is space only for some -Go-specific highlights here. -

    -

    -Concurrent programming in many environments is made difficult by the -subtleties required to implement correct access to shared variables. Go encourages -a different approach in which shared values are passed around on channels -and, in fact, never actively shared by separate threads of execution. -Only one goroutine has access to the value at any given time. -Data races cannot occur, by design. -To encourage this way of thinking we have reduced it to a slogan: -

    -
    -Do not communicate by sharing memory; -instead, share memory by communicating. -
    -

    -This approach can be taken too far. Reference counts may be best done -by putting a mutex around an integer variable, for instance. But as a -high-level approach, using channels to control access makes it easier -to write clear, correct programs. -

    -

    -One way to think about this model is to consider a typical single-threaded -program running on one CPU. It has no need for synchronization primitives. -Now run another such instance; it too needs no synchronization. Now let those -two communicate; if the communication is the synchronizer, there's still no need -for other synchronization. Unix pipelines, for example, fit this model -perfectly. Although Go's approach to concurrency originates in Hoare's -Communicating Sequential Processes (CSP), -it can also be seen as a type-safe generalization of Unix pipes. -

    - -

    Goroutines

    - -

    -They're called goroutines because the existing -terms—threads, coroutines, processes, and so on—convey -inaccurate connotations. A goroutine has a simple model: it is a -function executing concurrently with other goroutines in the same -address space. It is lightweight, costing little more than the -allocation of stack space. -And the stacks start small, so they are cheap, and grow -by allocating (and freeing) heap storage as required. -

    -

    -Goroutines are multiplexed onto multiple OS threads so if one should -block, such as while waiting for I/O, others continue to run. Their -design hides many of the complexities of thread creation and -management. -

    -

    -Prefix a function or method call with the go -keyword to run the call in a new goroutine. -When the call completes, the goroutine -exits, silently. (The effect is similar to the Unix shell's -& notation for running a command in the -background.) -

    -
    -go list.Sort()  // run list.Sort concurrently; don't wait for it.
    -
    -

    -A function literal can be handy in a goroutine invocation. -

    -
    -func Announce(message string, delay time.Duration) {
    -    go func() {
    -        time.Sleep(delay)
    -        fmt.Println(message)
    -    }()  // Note the parentheses - must call the function.
    -}
    -
    -

    -In Go, function literals are closures: the implementation makes -sure the variables referred to by the function survive as long as they are active. -

    -

    -These examples aren't too practical because the functions have no way of signaling -completion. For that, we need channels. -

    - -

    Channels

    - -

    -Like maps, channels are allocated with make, and -the resulting value acts as a reference to an underlying data structure. -If an optional integer parameter is provided, it sets the buffer size for the channel. -The default is zero, for an unbuffered or synchronous channel. -

    -
    -ci := make(chan int)            // unbuffered channel of integers
    -cj := make(chan int, 0)         // unbuffered channel of integers
    -cs := make(chan *os.File, 100)  // buffered channel of pointers to Files
    -
    -

    -Unbuffered channels combine communication—the exchange of a value—with -synchronization—guaranteeing that two calculations (goroutines) are in -a known state. -

    -

    -There are lots of nice idioms using channels. Here's one to get us started. -In the previous section we launched a sort in the background. A channel -can allow the launching goroutine to wait for the sort to complete. -

    -
    -c := make(chan int)  // Allocate a channel.
    -// Start the sort in a goroutine; when it completes, signal on the channel.
    -go func() {
    -    list.Sort()
    -    c <- 1  // Send a signal; value does not matter.
    -}()
    -doSomethingForAWhile()
    -<-c   // Wait for sort to finish; discard sent value.
    -
    -

    -Receivers always block until there is data to receive. -If the channel is unbuffered, the sender blocks until the receiver has -received the value. -If the channel has a buffer, the sender blocks only until the -value has been copied to the buffer; if the buffer is full, this -means waiting until some receiver has retrieved a value. -

    -

    -A buffered channel can be used like a semaphore, for instance to -limit throughput. In this example, incoming requests are passed -to handle, which sends a value into the channel, processes -the request, and then receives a value from the channel -to ready the “semaphore” for the next consumer. -The capacity of the channel buffer limits the number of -simultaneous calls to process. -

    -
    -var sem = make(chan int, MaxOutstanding)
    -
    -func handle(r *Request) {
    -    sem <- 1    // Wait for active queue to drain.
    -    process(r)  // May take a long time.
    -    <-sem       // Done; enable next request to run.
    -}
    -
    -func Serve(queue chan *Request) {
    -    for {
    -        req := <-queue
    -        go handle(req)  // Don't wait for handle to finish.
    -    }
    -}
    -
    - -

    -Once MaxOutstanding handlers are executing process, -any more will block trying to send into the filled channel buffer, -until one of the existing handlers finishes and receives from the buffer. -

    - -

    -This design has a problem, though: Serve -creates a new goroutine for -every incoming request, even though only MaxOutstanding -of them can run at any moment. -As a result, the program can consume unlimited resources if the requests come in too fast. -We can address that deficiency by changing Serve to -gate the creation of the goroutines. -Here's an obvious solution, but beware it has a bug we'll fix subsequently: -

    - -
    -func Serve(queue chan *Request) {
    -    for req := range queue {
    -        sem <- 1
    -        go func() {
    -            process(req) // Buggy; see explanation below.
    -            <-sem
    -        }()
    -    }
    -}
    - -

    -The bug is that in a Go for loop, the loop variable -is reused for each iteration, so the req -variable is shared across all goroutines. -That's not what we want. -We need to make sure that req is unique for each goroutine. -Here's one way to do that, passing the value of req as an argument -to the closure in the goroutine: -

    - -
    -func Serve(queue chan *Request) {
    -    for req := range queue {
    -        sem <- 1
    -        go func(req *Request) {
    -            process(req)
    -            <-sem
    -        }(req)
    -    }
    -}
    - -

    -Compare this version with the previous to see the difference in how -the closure is declared and run. -Another solution is just to create a new variable with the same -name, as in this example: -

    - -
    -func Serve(queue chan *Request) {
    -    for req := range queue {
    -        req := req // Create new instance of req for the goroutine.
    -        sem <- 1
    -        go func() {
    -            process(req)
    -            <-sem
    -        }()
    -    }
    -}
    - -

    -It may seem odd to write -

    - -
    -req := req
    -
    - -

    -but it's legal and idiomatic in Go to do this. -You get a fresh version of the variable with the same name, deliberately -shadowing the loop variable locally but unique to each goroutine. -

    - -

    -Going back to the general problem of writing the server, -another approach that manages resources well is to start a fixed -number of handle goroutines all reading from the request -channel. -The number of goroutines limits the number of simultaneous -calls to process. -This Serve function also accepts a channel on which -it will be told to exit; after launching the goroutines it blocks -receiving from that channel. -

    - -
    -func handle(queue chan *Request) {
    -    for r := range queue {
    -        process(r)
    -    }
    -}
    -
    -func Serve(clientRequests chan *Request, quit chan bool) {
    -    // Start handlers
    -    for i := 0; i < MaxOutstanding; i++ {
    -        go handle(clientRequests)
    -    }
    -    <-quit  // Wait to be told to exit.
    -}
    -
    - -

    Channels of channels

    -

    -One of the most important properties of Go is that -a channel is a first-class value that can be allocated and passed -around like any other. A common use of this property is -to implement safe, parallel demultiplexing. -

    -

    -In the example in the previous section, handle was -an idealized handler for a request but we didn't define the -type it was handling. If that type includes a channel on which -to reply, each client can provide its own path for the answer. -Here's a schematic definition of type Request. -

    -
    -type Request struct {
    -    args        []int
    -    f           func([]int) int
    -    resultChan  chan int
    -}
    -
    -

    -The client provides a function and its arguments, as well as -a channel inside the request object on which to receive the answer. -

    -
    -func sum(a []int) (s int) {
    -    for _, v := range a {
    -        s += v
    -    }
    -    return
    -}
    -
    -request := &Request{[]int{3, 4, 5}, sum, make(chan int)}
    -// Send request
    -clientRequests <- request
    -// Wait for response.
    -fmt.Printf("answer: %d\n", <-request.resultChan)
    -
    -

    -On the server side, the handler function is the only thing that changes. -

    -
    -func handle(queue chan *Request) {
    -    for req := range queue {
    -        req.resultChan <- req.f(req.args)
    -    }
    -}
    -
    -

    -There's clearly a lot more to do to make it realistic, but this -code is a framework for a rate-limited, parallel, non-blocking RPC -system, and there's not a mutex in sight. -

    - -

    Parallelization

    -

    -Another application of these ideas is to parallelize a calculation -across multiple CPU cores. If the calculation can be broken into -separate pieces that can execute independently, it can be parallelized, -with a channel to signal when each piece completes. -

    -

    -Let's say we have an expensive operation to perform on a vector of items, -and that the value of the operation on each item is independent, -as in this idealized example. -

    -
    -type Vector []float64
    -
    -// Apply the operation to v[i], v[i+1] ... up to v[n-1].
    -func (v Vector) DoSome(i, n int, u Vector, c chan int) {
    -    for ; i < n; i++ {
    -        v[i] += u.Op(v[i])
    -    }
    -    c <- 1    // signal that this piece is done
    -}
    -
    -

    -We launch the pieces independently in a loop, one per CPU. -They can complete in any order but it doesn't matter; we just -count the completion signals by draining the channel after -launching all the goroutines. -

    -
    -const numCPU = 4 // number of CPU cores
    -
    -func (v Vector) DoAll(u Vector) {
    -    c := make(chan int, numCPU)  // Buffering optional but sensible.
    -    for i := 0; i < numCPU; i++ {
    -        go v.DoSome(i*len(v)/numCPU, (i+1)*len(v)/numCPU, u, c)
    -    }
    -    // Drain the channel.
    -    for i := 0; i < numCPU; i++ {
    -        <-c    // wait for one task to complete
    -    }
    -    // All done.
    -}
    -
    -

    -Rather than create a constant value for numCPU, we can ask the runtime what -value is appropriate. -The function runtime.NumCPU -returns the number of hardware CPU cores in the machine, so we could write -

    -
    -var numCPU = runtime.NumCPU()
    -
    -

    -There is also a function -runtime.GOMAXPROCS, -which reports (or sets) -the user-specified number of cores that a Go program can have running -simultaneously. -It defaults to the value of runtime.NumCPU but can be -overridden by setting the similarly named shell environment variable -or by calling the function with a positive number. Calling it with -zero just queries the value. -Therefore if we want to honor the user's resource request, we should write -

    -
    -var numCPU = runtime.GOMAXPROCS(0)
    -
    -

    -Be sure not to confuse the ideas of concurrency—structuring a program -as independently executing components—and parallelism—executing -calculations in parallel for efficiency on multiple CPUs. -Although the concurrency features of Go can make some problems easy -to structure as parallel computations, Go is a concurrent language, -not a parallel one, and not all parallelization problems fit Go's model. -For a discussion of the distinction, see the talk cited in -this -blog post. - -

    A leaky buffer

    - -

    -The tools of concurrent programming can even make non-concurrent -ideas easier to express. Here's an example abstracted from an RPC -package. The client goroutine loops receiving data from some source, -perhaps a network. To avoid allocating and freeing buffers, it keeps -a free list, and uses a buffered channel to represent it. If the -channel is empty, a new buffer gets allocated. -Once the message buffer is ready, it's sent to the server on -serverChan. -

    -
    -var freeList = make(chan *Buffer, 100)
    -var serverChan = make(chan *Buffer)
    -
    -func client() {
    -    for {
    -        var b *Buffer
    -        // Grab a buffer if available; allocate if not.
    -        select {
    -        case b = <-freeList:
    -            // Got one; nothing more to do.
    -        default:
    -            // None free, so allocate a new one.
    -            b = new(Buffer)
    -        }
    -        load(b)              // Read next message from the net.
    -        serverChan <- b      // Send to server.
    -    }
    -}
    -
    -

    -The server loop receives each message from the client, processes it, -and returns the buffer to the free list. -

    -
    -func server() {
    -    for {
    -        b := <-serverChan    // Wait for work.
    -        process(b)
    -        // Reuse buffer if there's room.
    -        select {
    -        case freeList <- b:
    -            // Buffer on free list; nothing more to do.
    -        default:
    -            // Free list full, just carry on.
    -        }
    -    }
    -}
    -
    -

    -The client attempts to retrieve a buffer from freeList; -if none is available, it allocates a fresh one. -The server's send to freeList puts b back -on the free list unless the list is full, in which case the -buffer is dropped on the floor to be reclaimed by -the garbage collector. -(The default clauses in the select -statements execute when no other case is ready, -meaning that the selects never block.) -This implementation builds a leaky bucket free list -in just a few lines, relying on the buffered channel and -the garbage collector for bookkeeping. -

    - -

    Errors

    - -

    -Library routines must often return some sort of error indication to -the caller. -As mentioned earlier, Go's multivalue return makes it -easy to return a detailed error description alongside the normal -return value. -It is good style to use this feature to provide detailed error information. -For example, as we'll see, os.Open doesn't -just return a nil pointer on failure, it also returns an -error value that describes what went wrong. -

    - -

    -By convention, errors have type error, -a simple built-in interface. -

    -
    -type error interface {
    -    Error() string
    -}
    -
    -

    -A library writer is free to implement this interface with a -richer model under the covers, making it possible not only -to see the error but also to provide some context. -As mentioned, alongside the usual *os.File -return value, os.Open also returns an -error value. -If the file is opened successfully, the error will be nil, -but when there is a problem, it will hold an -os.PathError: -

    -
    -// 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) Error() string {
    -    return e.Op + " " + e.Path + ": " + e.Err.Error()
    -}
    -
    -

    -PathError's Error generates -a string like this: -

    -
    -open /etc/passwx: no such file or directory
    -
    -

    -Such an error, which includes the problematic file name, the -operation, and the operating system error it triggered, is useful even -if printed far from the call that caused it; -it is much more informative than the plain -"no such file or directory". -

    - -

    -When feasible, error strings should identify their origin, such as by having -a prefix naming the operation or package that generated the error. For example, in package -image, the string representation for a decoding error due to an -unknown format is "image: unknown format". -

    - -

    -Callers that care about the precise error details can -use a type switch or a type assertion to look for specific -errors and extract details. For PathErrors -this might include examining the internal Err -field for recoverable failures. -

    - -
    -for try := 0; try < 2; try++ {
    -    file, err = os.Create(filename)
    -    if err == nil {
    -        return
    -    }
    -    if e, ok := err.(*os.PathError); ok && e.Err == syscall.ENOSPC {
    -        deleteTempFiles()  // Recover some space.
    -        continue
    -    }
    -    return
    -}
    -
    - -

    -The second if statement here is another type assertion. -If it fails, ok will be false, and e -will be nil. -If it succeeds, ok will be true, which means the -error was of type *os.PathError, and then so is e, -which we can examine for more information about the error. -

    - -

    Panic

    - -

    -The usual way to report an error to a caller is to return an -error as an extra return value. The canonical -Read method is a well-known instance; it returns a byte -count and an error. But what if the error is -unrecoverable? Sometimes the program simply cannot continue. -

    - -

    -For this purpose, there is a built-in function panic -that in effect creates a run-time error that will stop the program -(but see the next section). The function takes a single argument -of arbitrary type—often a string—to be printed as the -program dies. It's also a way to indicate that something impossible has -happened, such as exiting an infinite loop. -

    - - -
    -// A toy implementation of cube root using Newton's method.
    -func CubeRoot(x float64) float64 {
    -    z := x/3   // Arbitrary initial value
    -    for i := 0; i < 1e6; i++ {
    -        prevz := z
    -        z -= (z*z*z-x) / (3*z*z)
    -        if veryClose(z, prevz) {
    -            return z
    -        }
    -    }
    -    // A million iterations has not converged; something is wrong.
    -    panic(fmt.Sprintf("CubeRoot(%g) did not converge", x))
    -}
    -
    - -

    -This is only an example but real library functions should -avoid panic. If the problem can be masked or worked -around, it's always better to let things continue to run rather -than taking down the whole program. One possible counterexample -is during initialization: if the library truly cannot set itself up, -it might be reasonable to panic, so to speak. -

    - -
    -var user = os.Getenv("USER")
    -
    -func init() {
    -    if user == "" {
    -        panic("no value for $USER")
    -    }
    -}
    -
    - -

    Recover

    - -

    -When panic is called, including implicitly for run-time -errors such as indexing a slice out of bounds or failing a type -assertion, it immediately stops execution of the current function -and begins unwinding the stack of the goroutine, running any deferred -functions along the way. If that unwinding reaches the top of the -goroutine's stack, the program dies. However, it is possible to -use the built-in function recover to regain control -of the goroutine and resume normal execution. -

    - -

    -A call to recover stops the unwinding and returns the -argument passed to panic. Because the only code that -runs while unwinding is inside deferred functions, recover -is only useful inside deferred functions. -

    - -

    -One application of recover is to shut down a failing goroutine -inside a server without killing the other executing goroutines. -

    - -
    -func server(workChan <-chan *Work) {
    -    for work := range workChan {
    -        go safelyDo(work)
    -    }
    -}
    -
    -func safelyDo(work *Work) {
    -    defer func() {
    -        if err := recover(); err != nil {
    -            log.Println("work failed:", err)
    -        }
    -    }()
    -    do(work)
    -}
    -
    - -

    -In this example, if do(work) panics, the result will be -logged and the goroutine will exit cleanly without disturbing the -others. There's no need to do anything else in the deferred closure; -calling recover handles the condition completely. -

    - -

    -Because recover always returns nil unless called directly -from a deferred function, deferred code can call library routines that themselves -use panic and recover without failing. As an example, -the deferred function in safelyDo might call a logging function before -calling recover, and that logging code would run unaffected -by the panicking state. -

    - -

    -With our recovery pattern in place, the do -function (and anything it calls) can get out of any bad situation -cleanly by calling panic. We can use that idea to -simplify error handling in complex software. Let's look at an -idealized version of a regexp package, which reports -parsing errors by calling panic with a local -error type. Here's the definition of Error, -an error method, and the Compile function. -

    - -
    -// Error is the type of a parse error; it satisfies the error interface.
    -type Error string
    -func (e Error) Error() string {
    -    return string(e)
    -}
    -
    -// error is a method of *Regexp that reports parsing errors by
    -// panicking with an Error.
    -func (regexp *Regexp) error(err string) {
    -    panic(Error(err))
    -}
    -
    -// Compile returns a parsed representation of the regular expression.
    -func Compile(str string) (regexp *Regexp, err error) {
    -    regexp = new(Regexp)
    -    // doParse will panic if there is a parse error.
    -    defer func() {
    -        if e := recover(); e != nil {
    -            regexp = nil    // Clear return value.
    -            err = e.(Error) // Will re-panic if not a parse error.
    -        }
    -    }()
    -    return regexp.doParse(str), nil
    -}
    -
    - -

    -If doParse panics, the recovery block will set the -return value to nil—deferred functions can modify -named return values. It will then check, in the assignment -to err, that the problem was a parse error by asserting -that it has the local type Error. -If it does not, the type assertion will fail, causing a run-time error -that continues the stack unwinding as though nothing had interrupted -it. -This check means that if something unexpected happens, such -as an index out of bounds, the code will fail even though we -are using panic and recover to handle -parse errors. -

    - -

    -With error handling in place, the error method (because it's a -method bound to a type, it's fine, even natural, for it to have the same name -as the builtin error type) -makes it easy to report parse errors without worrying about unwinding -the parse stack by hand: -

    - -
    -if pos == 0 {
    -    re.error("'*' illegal at start of expression")
    -}
    -
    - -

    -Useful though this pattern is, it should be used only within a package. -Parse turns its internal panic calls into -error values; it does not expose panics -to its client. That is a good rule to follow. -

    - -

    -By the way, this re-panic idiom changes the panic value if an actual -error occurs. However, both the original and new failures will be -presented in the crash report, so the root cause of the problem will -still be visible. Thus this simple re-panic approach is usually -sufficient—it's a crash after all—but if you want to -display only the original value, you can write a little more code to -filter unexpected problems and re-panic with the original error. -That's left as an exercise for the reader. -

    - - -

    A web server

    - -

    -Let's finish with a complete Go program, a web server. -This one is actually a kind of web re-server. -Google provides a service at chart.apis.google.com -that does automatic formatting of data into charts and graphs. -It's hard to use interactively, though, -because you need to put the data into the URL as a query. -The program here provides a nicer interface to one form of data: given a short piece of text, -it calls on the chart server to produce a QR code, a matrix of boxes that encode the -text. -That image can be grabbed with your cell phone's camera and interpreted as, -for instance, a URL, saving you typing the URL into the phone's tiny keyboard. -

    -

    -Here's the complete program. -An explanation follows. -

    -{{code "/doc/progs/eff_qr.go" `/package/` `$`}} -

    -The pieces up to main should be easy to follow. -The one flag sets a default HTTP port for our server. The template -variable templ is where the fun happens. It builds an HTML template -that will be executed by the server to display the page; more about -that in a moment. -

    -

    -The main function parses the flags and, using the mechanism -we talked about above, binds the function QR to the root path -for the server. Then http.ListenAndServe is called to start the -server; it blocks while the server runs. -

    -

    -QR just receives the request, which contains form data, and -executes the template on the data in the form value named s. -

    -

    -The template package html/template is powerful; -this program just touches on its capabilities. -In essence, it rewrites a piece of HTML text on the fly by substituting elements derived -from data items passed to templ.Execute, in this case the -form value. -Within the template text (templateStr), -double-brace-delimited pieces denote template actions. -The piece from {{html "{{if .}}"}} -to {{html "{{end}}"}} executes only if the value of the current data item, called . (dot), -is non-empty. -That is, when the string is empty, this piece of the template is suppressed. -

    -

    -The two snippets {{html "{{.}}"}} say to show the data presented to -the template—the query string—on the web page. -The HTML template package automatically provides appropriate escaping so the -text is safe to display. -

    -

    -The rest of the template string is just the HTML to show when the page loads. -If this is too quick an explanation, see the documentation -for the template package for a more thorough discussion. -

    -

    -And there you have it: a useful web server in a few lines of code plus some -data-driven HTML text. -Go is powerful enough to make a lot happen in a few lines. -

    - - diff --git a/doc/gccgo_contribute.html b/doc/gccgo_contribute.html deleted file mode 100644 index 395902d7cb..0000000000 --- a/doc/gccgo_contribute.html +++ /dev/null @@ -1,112 +0,0 @@ - - -

    Introduction

    - -

    -These are some notes on contributing to the gccgo frontend for GCC. -For information on contributing to parts of Go other than gccgo, -see Contributing to the Go project. For -information on building gccgo for yourself, -see Setting up and using gccgo. -For more of the gritty details on the process of doing development -with the gccgo frontend, -see the -file HACKING in the gofrontend repository. -

    - -

    Legal Prerequisites

    - -

    -You must follow the Go copyright -rules for all changes to the gccgo frontend and the associated -libgo library. Code that is part of GCC rather than gccgo must follow -the general GCC -contribution rules. -

    - -

    Code

    - -

    -The master sources for the gccgo frontend may be found at -https://go.googlesource.com/gofrontend. -They are mirrored -at https://github.com/golang/gofrontend. -The master sources are not buildable by themselves, but only in -conjunction with GCC (in the future, other compilers may be -supported). Changes made to the gccgo frontend are also applied to -the GCC source code repository hosted at gcc.gnu.org. In -the gofrontend repository, the go directory -is mirrored to the gcc/go/gofrontend directory in the GCC -repository, and the gofrontend libgo -directory is mirrored to the GCC libgo directory. In -addition, the test directory -from the main Go repository -is mirrored to the gcc/testsuite/go.test/test directory -in the GCC repository. -

    - -

    -Changes to these directories always flow from the master sources to -the GCC repository. The files should never be changed in the GCC -repository except by changing them in the master sources and mirroring -them. -

    - -

    -The gccgo frontend is written in C++. -It follows the GNU and GCC coding standards for C++. -In writing code for the frontend, follow the formatting of the -surrounding code. -Almost all GCC-specific code is not in the frontend proper and is -instead in the GCC sources in the gcc/go directory. -

    - -

    -The run-time library for gccgo is mostly the same as the library -in the main Go repository. -The library code in the Go repository is periodically merged into -the libgo/go directory of the gofrontend and -then the GCC repositories, using the shell -script libgo/merge.sh. Accordingly, most library changes -should be made in the main Go repository. The files outside -of libgo/go are gccgo-specific; that said, some of the -files in libgo/runtime are based on files -in src/runtime in the main Go repository. -

    - -

    Testing

    - -

    -All patches must be tested. A patch that introduces new failures is -not acceptable. -

    - -

    -To run the gccgo test suite, run make check-go in your -build directory. This will run various tests -under gcc/testsuite/go.* and will also run -the libgo testsuite. This copy of the tests from the -main Go repository is run using the DejaGNU script found -in gcc/testsuite/go.test/go-test.exp. -

    - -

    -Most new tests should be submitted to the main Go repository for later -mirroring into the GCC repository. If there is a need for specific -tests for gccgo, they should go in -the gcc/testsuite/go.go-torture -or gcc/testsuite/go.dg directories in the GCC repository. -

    - -

    Submitting Changes

    - -

    -Changes to the Go frontend should follow the same process as for the -main Go repository, only for the gofrontend project and -the gofrontend-dev@googlegroups.com mailing list -rather than the go project and the -golang-dev@googlegroups.com mailing list. Those changes -will then be merged into the GCC sources. -

    diff --git a/doc/gccgo_install.html b/doc/gccgo_install.html deleted file mode 100644 index c478a9ea2d..0000000000 --- a/doc/gccgo_install.html +++ /dev/null @@ -1,533 +0,0 @@ - - -

    -This document explains how to use gccgo, a compiler for -the Go language. The gccgo compiler is a new frontend -for GCC, the widely used GNU compiler. Although the -frontend itself is under a BSD-style license, gccgo is -normally used as part of GCC and is then covered by -the GNU General Public -License (the license covers gccgo itself as part of GCC; it -does not cover code generated by gccgo). -

    - -

    -Note that gccgo is not the gc compiler; see -the Installing Go instructions for that -compiler. -

    - -

    Releases

    - -

    -The simplest way to install gccgo is to install a GCC binary release -built to include Go support. GCC binary releases are available from -various -websites and are typically included as part of GNU/Linux -distributions. We expect that most people who build these binaries -will include Go support. -

    - -

    -The GCC 4.7.1 release and all later 4.7 releases include a complete -Go 1 compiler and libraries. -

    - -

    -Due to timing, the GCC 4.8.0 and 4.8.1 releases are close to but not -identical to Go 1.1. The GCC 4.8.2 release includes a complete Go -1.1.2 implementation. -

    - -

    -The GCC 4.9 releases include a complete Go 1.2 implementation. -

    - -

    -The GCC 5 releases include a complete implementation of the Go 1.4 -user libraries. The Go 1.4 runtime is not fully merged, but that -should not be visible to Go programs. -

    - -

    -The GCC 6 releases include a complete implementation of the Go 1.6.1 -user libraries. The Go 1.6 runtime is not fully merged, but that -should not be visible to Go programs. -

    - -

    -The GCC 7 releases include a complete implementation of the Go 1.8.1 -user libraries. As with earlier releases, the Go 1.8 runtime is not -fully merged, but that should not be visible to Go programs. -

    - -

    -The GCC 8 releases include a complete implementation of the Go 1.10.1 -release. The Go 1.10 runtime has now been fully merged into the GCC -development sources, and concurrent garbage collection is fully -supported. -

    - -

    -The GCC 9 releases include a complete implementation of the Go 1.12.2 -release. -

    - -

    Source code

    - -

    -If you cannot use a release, or prefer to build gccgo for yourself, the -gccgo source code is accessible via Git. The GCC web site has -instructions for getting the GCC -source code. The gccgo source code is included. As a convenience, a -stable version of the Go support is available in the -devel/gccgo branch of the main GCC code repository: -git://gcc.gnu.org/git/gcc.git. -This branch is periodically updated with stable Go compiler sources. -

    - -

    -Note that although gcc.gnu.org is the most convenient way -to get the source code for the Go frontend, it is not where the master -sources live. If you want to contribute changes to the Go frontend -compiler, see Contributing to -gccgo. -

    - - -

    Building

    - -

    -Building gccgo is just like building GCC -with one or two additional options. See -the instructions on the gcc web -site. When you run configure, add the -option --enable-languages=c,c++,go (along with other -languages you may want to build). If you are targeting a 32-bit x86, -then you will want to build gccgo to default to -supporting locked compare and exchange instructions; do this by also -using the configure option --with-arch=i586 -(or a newer architecture, depending on where you need your programs to -run). If you are targeting a 64-bit x86, but sometimes want to use -the -m32 option, then use the configure -option --with-arch-32=i586. -

    - -

    Gold

    - -

    -On x86 GNU/Linux systems the gccgo compiler is able to -use a small discontiguous stack for goroutines. This permits programs -to run many more goroutines, since each goroutine can use a relatively -small stack. Doing this requires using the gold linker version 2.22 -or later. You can either install GNU binutils 2.22 or later, or you -can build gold yourself. -

    - -

    -To build gold yourself, build the GNU binutils, -using --enable-gold=default when you run -the configure script. Before building, you must install -the flex and bison packages. A typical sequence would look like -this (you can replace /opt/gold with any directory to -which you have write access): -

    - -
    -git clone git://sourceware.org/git/binutils-gdb.git
    -mkdir binutils-objdir
    -cd binutils-objdir
    -../binutils-gdb/configure --enable-gold=default --prefix=/opt/gold
    -make
    -make install
    -
    - -

    -However you install gold, when you configure gccgo, use the -option --with-ld=GOLD_BINARY. -

    - -

    Prerequisites

    - -

    -A number of prerequisites are required to build GCC, as -described on -the gcc web -site. It is important to install all the prerequisites before -running the gcc configure script. -The prerequisite libraries can be conveniently downloaded using the -script contrib/download_prerequisites in the GCC sources. - -

    Build commands

    - -

    -Once all the prerequisites are installed, then a typical build and -install sequence would look like this (only use -the --with-ld option if you are using the gold linker as -described above): -

    - -
    -git clone --branch devel/gccgo git://gcc.gnu.org/git/gcc.git gccgo
    -mkdir objdir
    -cd objdir
    -../gccgo/configure --prefix=/opt/gccgo --enable-languages=c,c++,go --with-ld=/opt/gold/bin/ld
    -make
    -make install
    -
    - -

    Using gccgo

    - -

    -The gccgo compiler works like other gcc frontends. As of GCC 5 the gccgo -installation also includes a version of the go command, -which may be used to build Go programs as described at -https://golang.org/cmd/go. -

    - -

    -To compile a file without using the go command: -

    - -
    -gccgo -c file.go
    -
    - -

    -That produces file.o. To link files together to form an -executable: -

    - -
    -gccgo -o file file.o
    -
    - -

    -To run the resulting file, you will need to tell the program where to -find the compiled Go packages. There are a few ways to do this: -

    - -
      -
    • -

      -Set the LD_LIBRARY_PATH environment variable: -

      - -
      -LD_LIBRARY_PATH=${prefix}/lib/gcc/MACHINE/VERSION
      -[or]
      -LD_LIBRARY_PATH=${prefix}/lib64/gcc/MACHINE/VERSION
      -export LD_LIBRARY_PATH
      -
      - -

      -Here ${prefix} is the --prefix option used -when building gccgo. For a binary install this is -normally /usr. Whether to use lib -or lib64 depends on the target. -Typically lib64 is correct for x86_64 systems, -and lib is correct for other systems. The idea is to -name the directory where libgo.so is found. -

      - -
    • - -
    • -

      -Passing a -Wl,-R option when you link (replace lib with -lib64 if appropriate for your system): -

      - -
      -go build -gccgoflags -Wl,-R,${prefix}/lib/gcc/MACHINE/VERSION
      -[or]
      -gccgo -o file file.o -Wl,-R,${prefix}/lib/gcc/MACHINE/VERSION
      -
      -
    • - -
    • -

      -Use the -static-libgo option to link statically against -the compiled packages. -

      -
    • - -
    • -

      -Use the -static option to do a fully static link (the -default for the gc compiler). -

      -
    • -
    - -

    Options

    - -

    -The gccgo compiler supports all GCC options -that are language independent, notably the -O -and -g options. -

    - -

    -The -fgo-pkgpath=PKGPATH option may be used to set a -unique prefix for the package being compiled. -This option is automatically used by the go command, but you may want -to use it if you invoke gccgo directly. -This option is intended for use with large -programs that contain many packages, in order to allow multiple -packages to use the same identifier as the package name. -The PKGPATH may be any string; a good choice for the -string is the path used to import the package. -

    - -

    -The -I and -L options, which are synonyms -for the compiler, may be used to set the search path for finding -imports. -These options are not needed if you build with the go command. -

    - -

    Imports

    - -

    -When you compile a file that exports something, the export -information will be stored directly in the object file. -If you build with gccgo directly, rather than with the go command, -then when you import a package, you must tell gccgo how to find the -file. -

    - -

    -When you import the package FILE with gccgo, -it will look for the import data in the following files, and use the -first one that it finds. - -

      -
    • FILE.gox -
    • libFILE.so -
    • libFILE.a -
    • FILE.o -
    - -

    -FILE.gox, when used, will typically contain -nothing but export data. This can be generated from -FILE.o via -

    - -
    -objcopy -j .go_export FILE.o FILE.gox
    -
    - -

    -The gccgo compiler will look in the current -directory for import files. In more complex scenarios you -may pass the -I or -L option to -gccgo. Both options take directories to search. The --L option is also passed to the linker. -

    - -

    -The gccgo compiler does not currently (2015-06-15) record -the file name of imported packages in the object file. You must -arrange for the imported data to be linked into the program. -Again, this is not necessary when building with the go command. -

    - -
    -gccgo -c mypackage.go              # Exports mypackage
    -gccgo -c main.go                   # Imports mypackage
    -gccgo -o main main.o mypackage.o   # Explicitly links with mypackage.o
    -
    - -

    Debugging

    - -

    -If you use the -g option when you compile, you can run -gdb on your executable. The debugger has only limited -knowledge about Go. You can set breakpoints, single-step, -etc. You can print variables, but they will be printed as though they -had C/C++ types. For numeric types this doesn't matter. Go strings -and interfaces will show up as two-element structures. Go -maps and channels are always represented as C pointers to run-time -structures. -

    - -

    C Interoperability

    - -

    -When using gccgo there is limited interoperability with C, -or with C++ code compiled using extern "C". -

    - -

    Types

    - -

    -Basic types map directly: an int32 in Go is -an int32_t in C, an int64 is -an int64_t, etc. -The Go type int is an integer that is the same size as a -pointer, and as such corresponds to the C type intptr_t. -Go byte is equivalent to C unsigned char. -Pointers in Go are pointers in C. -A Go struct is the same as C struct with the -same fields and types. -

    - -

    -The Go string type is currently defined as a two-element -structure (this is subject to change): -

    - -
    -struct __go_string {
    -  const unsigned char *__data;
    -  intptr_t __length;
    -};
    -
    - -

    -You can't pass arrays between C and Go. However, a pointer to an -array in Go is equivalent to a C pointer to the -equivalent of the element type. -For example, Go *[10]int is equivalent to C int*, -assuming that the C pointer does point to 10 elements. -

    - -

    -A slice in Go is a structure. The current definition is -(this is subject to change): -

    - -
    -struct __go_slice {
    -  void *__values;
    -  intptr_t __count;
    -  intptr_t __capacity;
    -};
    -
    - -

    -The type of a Go function is a pointer to a struct (this is -subject to change). The first field in the -struct points to the code of the function, which will be equivalent to -a pointer to a C function whose parameter types are equivalent, with -an additional trailing parameter. The trailing parameter is the -closure, and the argument to pass is a pointer to the Go function -struct. - -When a Go function returns more than one value, the C function returns -a struct. For example, these functions are roughly equivalent: -

    - -
    -func GoFunction(int) (int, float64)
    -struct { int i; float64 f; } CFunction(int, void*)
    -
    - -

    -Go interface, channel, and map -types have no corresponding C type (interface is a -two-element struct and channel and map are -pointers to structs in C, but the structs are deliberately undocumented). C -enum types correspond to some integer type, but precisely -which one is difficult to predict in general; use a cast. C union -types have no corresponding Go type. C struct types containing -bitfields have no corresponding Go type. C++ class types have -no corresponding Go type. -

    - -

    -Memory allocation is completely different between C and Go, as Go uses -garbage collection. The exact guidelines in this area are undetermined, -but it is likely that it will be permitted to pass a pointer to allocated -memory from C to Go. The responsibility of eventually freeing the pointer -will remain with C side, and of course if the C side frees the pointer -while the Go side still has a copy the program will fail. When passing a -pointer from Go to C, the Go function must retain a visible copy of it in -some Go variable. Otherwise the Go garbage collector may delete the -pointer while the C function is still using it. -

    - -

    Function names

    - -

    -Go code can call C functions directly using a Go extension implemented -in gccgo: a function declaration may be preceded by -//extern NAME. For example, here is how the C function -open can be declared in Go: -

    - -
    -//extern open
    -func c_open(name *byte, mode int, perm int) int
    -
    - -

    -The C function naturally expects a NUL-terminated string, which in -Go is equivalent to a pointer to an array (not a slice!) of -byte with a terminating zero byte. So a sample call -from Go would look like (after importing the syscall package): -

    - -
    -var name = [4]byte{'f', 'o', 'o', 0};
    -i := c_open(&name[0], syscall.O_RDONLY, 0);
    -
    - -

    -(this serves as an example only, to open a file in Go please use Go's -os.Open function instead). -

    - -

    -Note that if the C function can block, such as in a call -to read, calling the C function may block the Go program. -Unless you have a clear understanding of what you are doing, all calls -between C and Go should be implemented through cgo or SWIG, as for -the gc compiler. -

    - -

    -The name of Go functions accessed from C is subject to change. At present -the name of a Go function that does not have a receiver is -prefix.package.Functionname. The prefix is set by -the -fgo-prefix option used when the package is compiled; -if the option is not used, the default is go. -To call the function from C you must set the name using -a GCC extension. -

    - -
    -extern int go_function(int) __asm__ ("myprefix.mypackage.Function");
    -
    - -

    -Automatic generation of Go declarations from C source code

    - -

    -The Go version of GCC supports automatically generating -Go declarations from C code. The facility is rather awkward, and most -users should use the cgo program with -the -gccgo option instead. -

    - -

    -Compile your C code as usual, and add the option --fdump-go-spec=FILENAME. This will create the -file FILENAME as a side effect of the -compilation. This file will contain Go declarations for the types, -variables and functions declared in the C code. C types that can not -be represented in Go will be recorded as comments in the Go code. The -generated file will not have a package declaration, but -can otherwise be compiled directly by gccgo. -

    - -

    -This procedure is full of unstated caveats and restrictions and we make no -guarantee that it will not change in the future. It is more useful as a -starting point for real Go code than as a regular procedure. -

    diff --git a/doc/go-logo-black.png b/doc/go-logo-black.png deleted file mode 100644 index 3077ebdad0..0000000000 Binary files a/doc/go-logo-black.png and /dev/null differ diff --git a/doc/go-logo-blue.png b/doc/go-logo-blue.png deleted file mode 100644 index 8d43a56775..0000000000 Binary files a/doc/go-logo-blue.png and /dev/null differ diff --git a/doc/go-logo-white.png b/doc/go-logo-white.png deleted file mode 100644 index fa29169fab..0000000000 Binary files a/doc/go-logo-white.png and /dev/null differ diff --git a/doc/go1.1.html b/doc/go1.1.html deleted file mode 100644 index f615c97e81..0000000000 --- a/doc/go1.1.html +++ /dev/null @@ -1,1099 +0,0 @@ - - -

    Introduction to Go 1.1

    - -

    -The release of Go version 1 (Go 1 or Go 1.0 for short) -in March of 2012 introduced a new period -of stability in the Go language and libraries. -That stability has helped nourish a growing community of Go users -and systems around the world. -Several "point" releases since -then—1.0.1, 1.0.2, and 1.0.3—have been issued. -These point releases fixed known bugs but made -no non-critical changes to the implementation. -

    - -

    -This new release, Go 1.1, keeps the promise -of compatibility but adds a couple of significant -(backwards-compatible, of course) language changes, has a long list -of (again, compatible) library changes, and -includes major work on the implementation of the compilers, -libraries, and run-time. -The focus is on performance. -Benchmarking is an inexact science at best, but we see significant, -sometimes dramatic speedups for many of our test programs. -We trust that many of our users' programs will also see improvements -just by updating their Go installation and recompiling. -

    - -

    -This document summarizes the changes between Go 1 and Go 1.1. -Very little if any code will need modification to run with Go 1.1, -although a couple of rare error cases surface with this release -and need to be addressed if they arise. -Details appear below; see the discussion of -64-bit ints and Unicode literals -in particular. -

    - -

    Changes to the language

    - -

    -The Go compatibility document promises -that programs written to the Go 1 language specification will continue to operate, -and those promises are maintained. -In the interest of firming up the specification, though, there are -details about some error cases that have been clarified. -There are also some new language features. -

    - -

    Integer division by zero

    - -

    -In Go 1, integer division by a constant zero produced a run-time panic: -

    - -
    -func f(x int) int {
    -	return x/0
    -}
    -
    - -

    -In Go 1.1, an integer division by constant zero is not a legal program, so it is a compile-time error. -

    - -

    Surrogates in Unicode literals

    - -

    -The definition of string and rune literals has been refined to exclude surrogate halves from the -set of valid Unicode code points. -See the Unicode section for more information. -

    - -

    Method values

    - -

    -Go 1.1 now implements -method values, -which are functions that have been bound to a specific receiver value. -For instance, given a -Writer -value w, -the expression -w.Write, -a method value, is a function that will always write to w; it is equivalent to -a function literal closing over w: -

    - -
    -func (p []byte) (n int, err error) {
    -	return w.Write(p)
    -}
    -
    - -

    -Method values are distinct from method expressions, which generate functions -from methods of a given type; the method expression (*bufio.Writer).Write -is equivalent to a function with an extra first argument, a receiver of type -(*bufio.Writer): -

    - -
    -func (w *bufio.Writer, p []byte) (n int, err error) {
    -	return w.Write(p)
    -}
    -
    - -

    -Updating: No existing code is affected; the change is strictly backward-compatible. -

    - -

    Return requirements

    - -

    -Before Go 1.1, a function that returned a value needed an explicit "return" -or call to panic at -the end of the function; this was a simple way to make the programmer -be explicit about the meaning of the function. But there are many cases -where a final "return" is clearly unnecessary, such as a function with -only an infinite "for" loop. -

    - -

    -In Go 1.1, the rule about final "return" statements is more permissive. -It introduces the concept of a -terminating statement, -a statement that is guaranteed to be the last one a function executes. -Examples include -"for" loops with no condition and "if-else" -statements in which each half ends in a "return". -If the final statement of a function can be shown syntactically to -be a terminating statement, no final "return" statement is needed. -

    - -

    -Note that the rule is purely syntactic: it pays no attention to the values in the -code and therefore requires no complex analysis. -

    - -

    -Updating: The change is backward-compatible, but existing code -with superfluous "return" statements and calls to panic may -be simplified manually. -Such code can be identified by go vet. -

    - -

    Changes to the implementations and tools

    - -

    Status of gccgo

    - -

    -The GCC release schedule does not coincide with the Go release schedule, so some skew is inevitable in -gccgo's releases. -The 4.8.0 version of GCC shipped in March, 2013 and includes a nearly-Go 1.1 version of gccgo. -Its library is a little behind the release, but the biggest difference is that method values are not implemented. -Sometime around July 2013, we expect 4.8.2 of GCC to ship with a gccgo -providing a complete Go 1.1 implementation. -

    - -

    Command-line flag parsing

    - -

    -In the gc toolchain, the compilers and linkers now use the -same command-line flag parsing rules as the Go flag package, a departure -from the traditional Unix flag parsing. This may affect scripts that invoke -the tool directly. -For example, -go tool 6c -Fw -Dfoo must now be written -go tool 6c -F -w -D foo. -

    - -

    Size of int on 64-bit platforms

    - -

    -The language allows the implementation to choose whether the int type and -uint types are 32 or 64 bits. Previous Go implementations made int -and uint 32 bits on all systems. Both the gc and gccgo implementations -now make -int and uint 64 bits on 64-bit platforms such as AMD64/x86-64. -Among other things, this enables the allocation of slices with -more than 2 billion elements on 64-bit platforms. -

    - -

    -Updating: -Most programs will be unaffected by this change. -Because Go does not allow implicit conversions between distinct -numeric types, -no programs will stop compiling due to this change. -However, programs that contain implicit assumptions -that int is only 32 bits may change behavior. -For example, this code prints a positive number on 64-bit systems and -a negative one on 32-bit systems: -

    - -
    -x := ^uint32(0) // x is 0xffffffff
    -i := int(x)     // i is -1 on 32-bit systems, 0xffffffff on 64-bit
    -fmt.Println(i)
    -
    - -

    Portable code intending 32-bit sign extension (yielding -1 on all systems) -would instead say: -

    - -
    -i := int(int32(x))
    -
    - -

    Heap size on 64-bit architectures

    - -

    -On 64-bit architectures, the maximum heap size has been enlarged substantially, -from a few gigabytes to several tens of gigabytes. -(The exact details depend on the system and may change.) -

    - -

    -On 32-bit architectures, the heap size has not changed. -

    - -

    -Updating: -This change should have no effect on existing programs beyond allowing them -to run with larger heaps. -

    - -

    Unicode

    - -

    -To make it possible to represent code points greater than 65535 in UTF-16, -Unicode defines surrogate halves, -a range of code points to be used only in the assembly of large values, and only in UTF-16. -The code points in that surrogate range are illegal for any other purpose. -In Go 1.1, this constraint is honored by the compiler, libraries, and run-time: -a surrogate half is illegal as a rune value, when encoded as UTF-8, or when -encoded in isolation as UTF-16. -When encountered, for example in converting from a rune to UTF-8, it is -treated as an encoding error and will yield the replacement rune, -utf8.RuneError, -U+FFFD. -

    - -

    -This program, -

    - -
    -import "fmt"
    -
    -func main() {
    -    fmt.Printf("%+q\n", string(0xD800))
    -}
    -
    - -

    -printed "\ud800" in Go 1.0, but prints "\ufffd" in Go 1.1. -

    - -

    -Surrogate-half Unicode values are now illegal in rune and string constants, so constants such as -'\ud800' and "\ud800" are now rejected by the compilers. -When written explicitly as UTF-8 encoded bytes, -such strings can still be created, as in "\xed\xa0\x80". -However, when such a string is decoded as a sequence of runes, as in a range loop, it will yield only utf8.RuneError -values. -

    - -

    -The Unicode byte order mark U+FEFF, encoded in UTF-8, is now permitted as the first -character of a Go source file. -Even though its appearance in the byte-order-free UTF-8 encoding is clearly unnecessary, -some editors add the mark as a kind of "magic number" identifying a UTF-8 encoded file. -

    - -

    -Updating: -Most programs will be unaffected by the surrogate change. -Programs that depend on the old behavior should be modified to avoid the issue. -The byte-order-mark change is strictly backward-compatible. -

    - -

    Race detector

    - -

    -A major addition to the tools is a race detector, a way to -find bugs in programs caused by concurrent access of the same -variable, where at least one of the accesses is a write. -This new facility is built into the go tool. -For now, it is only available on Linux, Mac OS X, and Windows systems with -64-bit x86 processors. -To enable it, set the -race flag when building or testing your program -(for instance, go test -race). -The race detector is documented in a separate article. -

    - -

    The gc assemblers

    - -

    -Due to the change of the int to 64 bits and -a new internal representation of functions, -the arrangement of function arguments on the stack has changed in the gc toolchain. -Functions written in assembly will need to be revised at least -to adjust frame pointer offsets. -

    - -

    -Updating: -The go vet command now checks that functions implemented in assembly -match the Go function prototypes they implement. -

    - -

    Changes to the go command

    - -

    -The go command has acquired several -changes intended to improve the experience for new Go users. -

    - -

    -First, when compiling, testing, or running Go code, the go command will now give more detailed error messages, -including a list of paths searched, when a package cannot be located. -

    - -
    -$ go build foo/quxx
    -can't load package: package foo/quxx: cannot find package "foo/quxx" in any of:
    -        /home/you/go/src/pkg/foo/quxx (from $GOROOT)
    -        /home/you/src/foo/quxx (from $GOPATH)
    -
    - -

    -Second, the go get command no longer allows $GOROOT -as the default destination when downloading package source. -To use the go get -command, a valid $GOPATH is now required. -

    - -
    -$ GOPATH= go get code.google.com/p/foo/quxx
    -package code.google.com/p/foo/quxx: cannot download, $GOPATH not set. For more details see: go help gopath
    -
    - -

    -Finally, as a result of the previous change, the go get command will also fail -when $GOPATH and $GOROOT are set to the same value. -

    - -
    -$ GOPATH=$GOROOT go get code.google.com/p/foo/quxx
    -warning: GOPATH set to GOROOT (/home/you/go) has no effect
    -package code.google.com/p/foo/quxx: cannot download, $GOPATH must not be set to $GOROOT. For more details see: go help gopath
    -
    - -

    Changes to the go test command

    - -

    -The go test -command no longer deletes the binary when run with profiling enabled, -to make it easier to analyze the profile. -The implementation sets the -c flag automatically, so after running, -

    - -
    -$ go test -cpuprofile cpuprof.out mypackage
    -
    - -

    -the file mypackage.test will be left in the directory where go test was run. -

    - -

    -The go test -command can now generate profiling information -that reports where goroutines are blocked, that is, -where they tend to stall waiting for an event such as a channel communication. -The information is presented as a -blocking profile -enabled with the --blockprofile -option of -go test. -Run go help test for more information. -

    - -

    Changes to the go fix command

    - -

    -The fix command, usually run as -go fix, no longer applies fixes to update code from -before Go 1 to use Go 1 APIs. -To update pre-Go 1 code to Go 1.1, use a Go 1.0 toolchain -to convert the code to Go 1.0 first. -

    - -

    Build constraints

    - -

    -The "go1.1" tag has been added to the list of default -build constraints. -This permits packages to take advantage of the new features in Go 1.1 while -remaining compatible with earlier versions of Go. -

    - -

    -To build a file only with Go 1.1 and above, add this build constraint: -

    - -
    -// +build go1.1
    -
    - -

    -To build a file only with Go 1.0.x, use the converse constraint: -

    - -
    -// +build !go1.1
    -
    - -

    Additional platforms

    - -

    -The Go 1.1 toolchain adds experimental support for freebsd/arm, -netbsd/386, netbsd/amd64, netbsd/arm, -openbsd/386 and openbsd/amd64 platforms. -

    - -

    -An ARMv6 or later processor is required for freebsd/arm or -netbsd/arm. -

    - -

    -Go 1.1 adds experimental support for cgo on linux/arm. -

    - -

    Cross compilation

    - -

    -When cross-compiling, the go tool will disable cgo -support by default. -

    - -

    -To explicitly enable cgo, set CGO_ENABLED=1. -

    - -

    Performance

    - -

    -The performance of code compiled with the Go 1.1 gc tool suite should be noticeably -better for most Go programs. -Typical improvements relative to Go 1.0 seem to be about 30%-40%, sometimes -much more, but occasionally less or even non-existent. -There are too many small performance-driven tweaks through the tools and libraries -to list them all here, but the following major changes are worth noting: -

    - -
      -
    • The gc compilers generate better code in many cases, most noticeably for -floating point on the 32-bit Intel architecture.
    • -
    • The gc compilers do more in-lining, including for some operations -in the run-time such as append -and interface conversions.
    • -
    • There is a new implementation of Go maps with significant reduction in -memory footprint and CPU time.
    • -
    • The garbage collector has been made more parallel, which can reduce -latencies for programs running on multiple CPUs.
    • -
    • The garbage collector is also more precise, which costs a small amount of -CPU time but can reduce the size of the heap significantly, especially -on 32-bit architectures.
    • -
    • Due to tighter coupling of the run-time and network libraries, fewer -context switches are required on network operations.
    • -
    - -

    Changes to the standard library

    - -

    bufio.Scanner

    - -

    -The various routines to scan textual input in the -bufio -package, -ReadBytes, -ReadString -and particularly -ReadLine, -are needlessly complex to use for simple purposes. -In Go 1.1, a new type, -Scanner, -has been added to make it easier to do simple tasks such as -read the input as a sequence of lines or space-delimited words. -It simplifies the problem by terminating the scan on problematic -input such as pathologically long lines, and having a simple -default: line-oriented input, with each line stripped of its terminator. -Here is code to reproduce the input a line at a time: -

    - -
    -scanner := bufio.NewScanner(os.Stdin)
    -for scanner.Scan() {
    -    fmt.Println(scanner.Text()) // Println will add back the final '\n'
    -}
    -if err := scanner.Err(); err != nil {
    -    fmt.Fprintln(os.Stderr, "reading standard input:", err)
    -}
    -
    - -

    -Scanning behavior can be adjusted through a function to control subdividing the input -(see the documentation for SplitFunc), -but for tough problems or the need to continue past errors, the older interface -may still be required. -

    - -

    net

    - -

    -The protocol-specific resolvers in the net package were formerly -lax about the network name passed in. -Although the documentation was clear -that the only valid networks for -ResolveTCPAddr -are "tcp", -"tcp4", and "tcp6", the Go 1.0 implementation silently accepted any string. -The Go 1.1 implementation returns an error if the network is not one of those strings. -The same is true of the other protocol-specific resolvers ResolveIPAddr, -ResolveUDPAddr, and -ResolveUnixAddr. -

    - -

    -The previous implementation of -ListenUnixgram -returned a -UDPConn as -a representation of the connection endpoint. -The Go 1.1 implementation instead returns a -UnixConn -to allow reading and writing -with its -ReadFrom -and -WriteTo -methods. -

    - -

    -The data structures -IPAddr, -TCPAddr, and -UDPAddr -add a new string field called Zone. -Code using untagged composite literals (e.g. net.TCPAddr{ip, port}) -instead of tagged literals (net.TCPAddr{IP: ip, Port: port}) -will break due to the new field. -The Go 1 compatibility rules allow this change: client code must use tagged literals to avoid such breakages. -

    - -

    -Updating: -To correct breakage caused by the new struct field, -go fix will rewrite code to add tags for these types. -More generally, go vet will identify composite literals that -should be revised to use field tags. -

    - -

    reflect

    - -

    -The reflect package has several significant additions. -

    - -

    -It is now possible to run a "select" statement using -the reflect package; see the description of -Select -and -SelectCase -for details. -

    - -

    -The new method -Value.Convert -(or -Type.ConvertibleTo) -provides functionality to execute a Go conversion or type assertion operation -on a -Value -(or test for its possibility). -

    - -

    -The new function -MakeFunc -creates a wrapper function to make it easier to call a function with existing -Values, -doing the standard Go conversions among the arguments, for instance -to pass an actual int to a formal interface{}. -

    - -

    -Finally, the new functions -ChanOf, -MapOf -and -SliceOf -construct new -Types -from existing types, for example to construct the type []T given -only T. -

    - - -

    time

    -

    -On FreeBSD, Linux, NetBSD, OS X and OpenBSD, previous versions of the -time package -returned times with microsecond precision. -The Go 1.1 implementation on these -systems now returns times with nanosecond precision. -Programs that write to an external format with microsecond precision -and read it back, expecting to recover the original value, will be affected -by the loss of precision. -There are two new methods of Time, -Round -and -Truncate, -that can be used to remove precision from a time before passing it to -external storage. -

    - -

    -The new method -YearDay -returns the one-indexed integral day number of the year specified by the time value. -

    - -

    -The -Timer -type has a new method -Reset -that modifies the timer to expire after a specified duration. -

    - -

    -Finally, the new function -ParseInLocation -is like the existing -Parse -but parses the time in the context of a location (time zone), ignoring -time zone information in the parsed string. -This function addresses a common source of confusion in the time API. -

    - -

    -Updating: -Code that needs to read and write times using an external format with -lower precision should be modified to use the new methods. -

    - -

    Exp and old subtrees moved to go.exp and go.text subrepositories

    - -

    -To make it easier for binary distributions to access them if desired, the exp -and old source subtrees, which are not included in binary distributions, -have been moved to the new go.exp subrepository at -code.google.com/p/go.exp. To access the ssa package, -for example, run -

    - -
    -$ go get code.google.com/p/go.exp/ssa
    -
    - -

    -and then in Go source, -

    - -
    -import "code.google.com/p/go.exp/ssa"
    -
    - -

    -The old package exp/norm has also been moved, but to a new repository -go.text, where the Unicode APIs and other text-related packages will -be developed. -

    - -

    New packages

    - -

    -There are three new packages. -

    - -
      -
    • -The go/format package provides -a convenient way for a program to access the formatting capabilities of the -go fmt command. -It has two functions, -Node to format a Go parser -Node, -and -Source -to reformat arbitrary Go source code into the standard format as provided by the -go fmt command. -
    • - -
    • -The net/http/cookiejar package provides the basics for managing HTTP cookies. -
    • - -
    • -The runtime/race package provides low-level facilities for data race detection. -It is internal to the race detector and does not otherwise export any user-visible functionality. -
    • -
    - -

    Minor changes to the library

    - -

    -The following list summarizes a number of minor changes to the library, mostly additions. -See the relevant package documentation for more information about each change. -

    - -
      -
    • -The bytes package has two new functions, -TrimPrefix -and -TrimSuffix, -with self-evident properties. -Also, the Buffer type -has a new method -Grow that -provides some control over memory allocation inside the buffer. -Finally, the -Reader type now has a -WriteTo method -so it implements the -io.WriterTo interface. -
    • - -
    • -The compress/gzip package has -a new Flush -method for its -Writer -type that flushes its underlying flate.Writer. -
    • - -
    • -The crypto/hmac package has a new function, -Equal, to compare two MACs. -
    • - -
    • -The crypto/x509 package -now supports PEM blocks (see -DecryptPEMBlock for instance), -and a new function -ParseECPrivateKey to parse elliptic curve private keys. -
    • - -
    • -The database/sql package -has a new -Ping -method for its -DB -type that tests the health of the connection. -
    • - -
    • -The database/sql/driver package -has a new -Queryer -interface that a -Conn -may implement to improve performance. -
    • - -
    • -The encoding/json package's -Decoder -has a new method -Buffered -to provide access to the remaining data in its buffer, -as well as a new method -UseNumber -to unmarshal a value into the new type -Number, -a string, rather than a float64. -
    • - -
    • -The encoding/xml package -has a new function, -EscapeText, -which writes escaped XML output, -and a method on -Encoder, -Indent, -to specify indented output. -
    • - -
    • -In the go/ast package, a -new type CommentMap -and associated methods makes it easier to extract and process comments in Go programs. -
    • - -
    • -In the go/doc package, -the parser now keeps better track of stylized annotations such as TODO(joe) -throughout the code, -information that the godoc -command can filter or present according to the value of the -notes flag. -
    • - -
    • -The undocumented and only partially implemented "noescape" feature of the -html/template -package has been removed; programs that depend on it will break. -
    • - -
    • -The image/jpeg package now -reads progressive JPEG files and handles a few more subsampling configurations. -
    • - -
    • -The io package now exports the -io.ByteWriter interface to capture the common -functionality of writing a byte at a time. -It also exports a new error, ErrNoProgress, -used to indicate a Read implementation is looping without delivering data. -
    • - -
    • -The log/syslog package now provides better support -for OS-specific logging features. -
    • - -
    • -The math/big package's -Int type -now has methods -MarshalJSON -and -UnmarshalJSON -to convert to and from a JSON representation. -Also, -Int -can now convert directly to and from a uint64 using -Uint64 -and -SetUint64, -while -Rat -can do the same with float64 using -Float64 -and -SetFloat64. -
    • - -
    • -The mime/multipart package -has a new method for its -Writer, -SetBoundary, -to define the boundary separator used to package the output. -The Reader also now -transparently decodes any quoted-printable parts and removes -the Content-Transfer-Encoding header when doing so. -
    • - -
    • -The -net package's -ListenUnixgram -function has changed return types: it now returns a -UnixConn -rather than a -UDPConn, which was -clearly a mistake in Go 1.0. -Since this API change fixes a bug, it is permitted by the Go 1 compatibility rules. -
    • - -
    • -The net package includes a new type, -Dialer, to supply options to -Dial. -
    • - -
    • -The net package adds support for -link-local IPv6 addresses with zone qualifiers, such as fe80::1%lo0. -The address structures IPAddr, -UDPAddr, and -TCPAddr -record the zone in a new field, and functions that expect string forms of these addresses, such as -Dial, -ResolveIPAddr, -ResolveUDPAddr, and -ResolveTCPAddr, -now accept the zone-qualified form. -
    • - -
    • -The net package adds -LookupNS to its suite of resolving functions. -LookupNS returns the NS records for a host name. -
    • - -
    • -The net package adds protocol-specific -packet reading and writing methods to -IPConn -(ReadMsgIP -and WriteMsgIP) and -UDPConn -(ReadMsgUDP and -WriteMsgUDP). -These are specialized versions of PacketConn's -ReadFrom and WriteTo methods that provide access to out-of-band data associated -with the packets. -
    • - -
    • -The net package adds methods to -UnixConn to allow closing half of the connection -(CloseRead and -CloseWrite), -matching the existing methods of TCPConn. -
    • - -
    • -The net/http package includes several new additions. -ParseTime parses a time string, trying -several common HTTP time formats. -The PostFormValue method of -Request is like -FormValue but ignores URL parameters. -The CloseNotifier interface provides a mechanism -for a server handler to discover when a client has disconnected. -The ServeMux type now has a -Handler method to access a path's -Handler without executing it. -The Transport can now cancel an in-flight request with -CancelRequest. -Finally, the Transport is now more aggressive at closing TCP connections when -a Response.Body is closed before -being fully consumed. -
    • - -
    • -The net/mail package has two new functions, -ParseAddress and -ParseAddressList, -to parse RFC 5322-formatted mail addresses into -Address structures. -
    • - -
    • -The net/smtp package's -Client type has a new method, -Hello, -which transmits a HELO or EHLO message to the server. -
    • - -
    • -The net/textproto package -has two new functions, -TrimBytes and -TrimString, -which do ASCII-only trimming of leading and trailing spaces. -
    • - -
    • -The new method os.FileMode.IsRegular makes it easy to ask if a file is a plain file. -
    • - -
    • -The os/signal package has a new function, -Stop, which stops the package delivering -any further signals to the channel. -
    • - -
    • -The regexp package -now supports Unix-original leftmost-longest matches through the -Regexp.Longest -method, while -Regexp.Split slices -strings into pieces based on separators defined by the regular expression. -
    • - -
    • -The runtime/debug package -has three new functions regarding memory usage. -The FreeOSMemory -function triggers a run of the garbage collector and then attempts to return unused -memory to the operating system; -the ReadGCStats -function retrieves statistics about the collector; and -SetGCPercent -provides a programmatic way to control how often the collector runs, -including disabling it altogether. -
    • - -
    • -The sort package has a new function, -Reverse. -Wrapping the argument of a call to -sort.Sort -with a call to Reverse causes the sort order to be reversed. -
    • - -
    • -The strings package has two new functions, -TrimPrefix -and -TrimSuffix -with self-evident properties, and the new method -Reader.WriteTo so the -Reader -type now implements the -io.WriterTo interface. -
    • - -
    • -The syscall package's -Fchflags function on various BSDs -(including Darwin) has changed signature. -It now takes an int as the first parameter instead of a string. -Since this API change fixes a bug, it is permitted by the Go 1 compatibility rules. -
    • -
    • -The syscall package also has received many updates -to make it more inclusive of constants and system calls for each supported operating system. -
    • - -
    • -The testing package now automates the generation of allocation -statistics in tests and benchmarks using the new -AllocsPerRun function. And the -ReportAllocs -method on testing.B will enable printing of -memory allocation statistics for the calling benchmark. It also introduces the -AllocsPerOp method of -BenchmarkResult. -There is also a new -Verbose function to test the state of the -v -command-line flag, -and a new -Skip method of -testing.B and -testing.T -to simplify skipping an inappropriate test. -
    • - -
    • -In the text/template -and -html/template packages, -templates can now use parentheses to group the elements of pipelines, simplifying the construction of complex pipelines. -Also, as part of the new parser, the -Node interface got two new methods to provide -better error reporting. -Although this violates the Go 1 compatibility rules, -no existing code should be affected because this interface is explicitly intended only to be used -by the -text/template -and -html/template -packages and there are safeguards to guarantee that. -
    • - -
    • -The implementation of the unicode package has been updated to Unicode version 6.2.0. -
    • - -
    • -In the unicode/utf8 package, -the new function ValidRune reports whether the rune is a valid Unicode code point. -To be valid, a rune must be in range and not be a surrogate half. -
    • -
    diff --git a/doc/go1.10.html b/doc/go1.10.html deleted file mode 100644 index 853f874ded..0000000000 --- a/doc/go1.10.html +++ /dev/null @@ -1,1448 +0,0 @@ - - - - - - -

    Introduction to Go 1.10

    - -

    -The latest Go release, version 1.10, arrives six months after Go 1.9. -Most of its changes are in the implementation of the toolchain, runtime, and libraries. -As always, the release maintains the Go 1 promise of compatibility. -We expect almost all Go programs to continue to compile and run as before. -

    - -

    -This release improves caching of built packages, -adds caching of successful test results, -runs vet automatically during tests, -and -permits passing string values directly between Go and C using cgo. -A new hard-coded set of safe compiler options may cause -unexpected invalid -flag errors in code that built successfully with older -releases. -

    - -

    Changes to the language

    - -

    -There are no significant changes to the language specification. -

    - -

    -A corner case involving shifts of untyped constants has been clarified, -and as a result the compilers have been updated to allow the index expression -x[1.0 << s] where s is an unsigned integer; -the go/types package already did. -

    - -

    -The grammar for method expressions has been updated to relax the -syntax to allow any type expression as a receiver; -this matches what the compilers were already implementing. -For example, struct{io.Reader}.Read is a valid, if unusual, -method expression that the compilers already accepted and is -now permitted by the language grammar. -

    - -

    Ports

    - -

    -There are no new supported operating systems or processor architectures in this release. -Most of the work has focused on strengthening the support for existing ports, -in particular new instructions in the assembler -and improvements to the code generated by the compilers. -

    - -

    -As announced in the Go 1.9 release notes, -Go 1.10 now requires FreeBSD 10.3 or later; -support for FreeBSD 9.3 has been removed. -

    - -

    -Go now runs on NetBSD again but requires the unreleased NetBSD 8. -Only GOARCH amd64 and 386 have -been fixed. The arm port is still broken. -

    - -

    -On 32-bit MIPS systems, the new environment variable settings -GOMIPS=hardfloat (the default) and -GOMIPS=softfloat select whether to use -hardware instructions or software emulation for floating-point computations. -

    - -

    -Go 1.10 is the last release that will run on OpenBSD 6.0. -Go 1.11 will require OpenBSD 6.2. -

    - -

    -Go 1.10 is the last release that will run on OS X 10.8 Mountain Lion or OS X 10.9 Mavericks. -Go 1.11 will require OS X 10.10 Yosemite or later. -

    - -

    -Go 1.10 is the last release that will run on Windows XP or Windows Vista. -Go 1.11 will require Windows 7 or later. -

    - -

    Tools

    - -

    Default GOROOT & GOTMPDIR

    - -

    -If the environment variable $GOROOT is unset, -the go tool previously used the default GOROOT -set during toolchain compilation. -Now, before falling back to that default, the go tool attempts to -deduce GOROOT from its own executable path. -This allows binary distributions to be unpacked anywhere in the -file system and then be used without setting GOROOT -explicitly. -

    - -

    -By default, the go tool creates its temporary files and directories -in the system temporary directory (for example, $TMPDIR on Unix). -If the new environment variable $GOTMPDIR is set, -the go tool will creates its temporary files and directories in that directory instead. -

    - -

    Build & Install

    - -

    -The go build command now detects out-of-date packages -purely based on the content of source files, specified build flags, and metadata stored in the compiled packages. -Modification times are no longer consulted or relevant. -The old advice to add -a to force a rebuild in cases where -the modification times were misleading for one reason or another -(for example, changes in build flags) is no longer necessary: -builds now always detect when packages must be rebuilt. -(If you observe otherwise, please file a bug.) -

    - -

    -The go build -asmflags, -gcflags, -gccgoflags, and -ldflags options -now apply by default only to the packages listed directly on the command line. -For example, go build -gcflags=-m mypkg -passes the compiler the -m flag when building mypkg -but not its dependencies. -The new, more general form -asmflags=pattern=flags (and similarly for the others) -applies the flags only to the packages matching the pattern. -For example: go install -ldflags=cmd/gofmt=-X=main.version=1.2.3 cmd/... -installs all the commands matching cmd/... but only applies the -X option -to the linker flags for cmd/gofmt. -For more details, see go help build. -

    - -

    -The go build command now maintains a cache of -recently built packages, separate from the installed packages in $GOROOT/pkg or $GOPATH/pkg. -The effect of the cache should be to speed builds that do not explicitly install packages -or when switching between different copies of source code (for example, when changing -back and forth between different branches in a version control system). -The old advice to add the -i flag for speed, as in go build -i -or go test -i, -is no longer necessary: builds run just as fast without -i. -For more details, see go help cache. -

    - -

    -The go install command now installs only the -packages and commands listed directly on the command line. -For example, go install cmd/gofmt -installs the gofmt program but not any of the packages on which it depends. -The new build cache makes future commands still run as quickly as if the -dependencies had been installed. -To force the installation of dependencies, use the new -go install -i flag. -Installing dependency packages should not be necessary in general, -and the very concept of installed packages may disappear in a future release. -

    - -

    -Many details of the go build implementation have changed to support these improvements. -One new requirement implied by these changes is that -binary-only packages must now declare accurate import blocks in their -stub source code, so that those imports can be made available when -linking a program using the binary-only package. -For more details, see go help filetype. -

    - -

    Test

    - -

    -The go test command now caches test results: -if the test executable and command line match a previous run -and the files and environment variables consulted by that run -have not changed either, go test will print -the previous test output, replacing the elapsed time with the string “(cached).” -Test caching applies only to successful test results; -only to go test -commands with an explicit list of packages; and -only to command lines using a subset of the --cpu, -list, -parallel, --run, -short, and -v test flags. -The idiomatic way to bypass test caching is to use -count=1. -

    - -

    -The go test command now automatically runs -go vet on the package being tested, -to identify significant problems before running the test. -Any such problems are treated like build errors and prevent execution of the test. -Only a high-confidence subset of the available go vet -checks are enabled for this automatic check. -To disable the running of go vet, use -go test -vet=off. -

    - -

    -The go test -coverpkg flag now -interprets its argument as a comma-separated list of patterns to match against -the dependencies of each test, not as a list of packages to load anew. -For example, go test -coverpkg=all -is now a meaningful way to run a test with coverage enabled for the test package -and all its dependencies. -Also, the go test -coverprofile option is now -supported when running multiple tests. -

    - -

    -In case of failure due to timeout, tests are now more likely to write their profiles before exiting. -

    - -

    -The go test command now always -merges the standard output and standard error from a given test binary execution -and writes both to go test's standard output. -In past releases, go test only applied this -merging most of the time. -

    - -

    -The go test -v output -now includes PAUSE and CONT status update -lines to mark when parallel tests pause and continue. -

    - -

    -The new go test -failfast flag -disables running additional tests after any test fails. -Note that tests running in parallel with the failing test are allowed to complete. -

    - -

    -Finally, the new go test -json flag -filters test output through the new command -go tool test2json -to produce a machine-readable JSON-formatted description of test execution. -This allows the creation of rich presentations of test execution -in IDEs and other tools. -

    - - -

    -For more details about all these changes, -see go help test -and the test2json documentation. -

    - -

    Cgo

    - -

    -Options specified by cgo using #cgo CFLAGS and the like -are now checked against a list of permitted options. -This closes a security hole in which a downloaded package uses -compiler options like --fplugin -to run arbitrary code on the machine where it is being built. -This can cause a build error such as invalid flag in #cgo CFLAGS. -For more background, and how to handle this error, see -https://golang.org/s/invalidflag. -

    - -

    -Cgo now implements a C typedef like “typedef X Y” using a Go type alias, -so that Go code may use the types C.X and C.Y interchangeably. -It also now supports the use of niladic function-like macros. -Also, the documentation has been updated to clarify that -Go structs and Go arrays are not supported in the type signatures of cgo-exported functions. -

    - -

    -Cgo now supports direct access to Go string values from C. -Functions in the C preamble may use the type _GoString_ -to accept a Go string as an argument. -C code may call _GoStringLen and _GoStringPtr -for direct access to the contents of the string. -A value of type _GoString_ -may be passed in a call to an exported Go function that takes an argument of Go type string. -

    - -

    -During toolchain bootstrap, the environment variables CC and CC_FOR_TARGET specify -the default C compiler that the resulting toolchain will use for host and target builds, respectively. -However, if the toolchain will be used with multiple targets, it may be necessary to specify a different C compiler for each -(for example, a different compiler for darwin/arm64 versus linux/ppc64le). -The new set of environment variables CC_FOR_goos_goarch -allows specifying a different default C compiler for each target. -Note that these variables only apply during toolchain bootstrap, -to set the defaults used by the resulting toolchain. -Later go build commands use the CC environment -variable or else the built-in default. -

    - -

    -Cgo now translates some C types that would normally map to a pointer -type in Go, to a uintptr instead. These types include -the CFTypeRef hierarchy in Darwin's CoreFoundation -framework and the jobject hierarchy in Java's JNI -interface. -

    - -

    -These types must be uintptr on the Go side because they -would otherwise confuse the Go garbage collector; they are sometimes -not really pointers but data structures encoded in a pointer-sized integer. -Pointers to Go memory must not be stored in these uintptr values. -

    - -

    -Because of this change, values of the affected types need to be -zero-initialized with the constant 0 instead of the -constant nil. Go 1.10 provides gofix -modules to help with that rewrite: -

    - -
    -go tool fix -r cftype <pkg>
    -go tool fix -r jni <pkg>
    -
    - -

    -For more details, see the cgo documentation. -

    - -

    Doc

    - -

    -The go doc tool now adds functions returning slices of T or *T -to the display of type T, similar to the existing behavior for functions returning single T or *T results. -For example: -

    - -
    -$ go doc mail.Address
    -package mail // import "net/mail"
    -
    -type Address struct {
    -	Name    string
    -	Address string
    -}
    -    Address represents a single mail address.
    -
    -func ParseAddress(address string) (*Address, error)
    -func ParseAddressList(list string) ([]*Address, error)
    -func (a *Address) String() string
    -$
    -
    - -

    -Previously, ParseAddressList was only shown in the package overview (go doc mail). -

    - -

    Fix

    - -

    -The go fix tool now replaces imports of "golang.org/x/net/context" -with "context". -(Forwarding aliases in the former make it completely equivalent to the latter when using Go 1.9 or later.) -

    - -

    Get

    - -

    -The go get command now supports Fossil source code repositories. -

    - -

    Pprof

    - -

    -The blocking and mutex profiles produced by the runtime/pprof package -now include symbol information, so they can be viewed -in go tool pprof -without the binary that produced the profile. -(All other profile types were changed to include symbol information in Go 1.9.) -

    - -

    -The go tool pprof -profile visualizer has been updated to git version 9e20b5b (2017-11-08) -from github.com/google/pprof, -which includes an updated web interface. -

    - -

    Vet

    - -

    -The go vet command now always has access to -complete, up-to-date type information when checking packages, even for packages using cgo or vendored imports. -The reports should be more accurate as a result. -Note that only go vet has access to this information; -the more low-level go tool vet does not -and should be avoided except when working on vet itself. -(As of Go 1.9, go vet provides access to all the same flags as -go tool vet.) -

    - -

    Diagnostics

    - -

    -This release includes a new overview of available Go program diagnostic tools. -

    - -

    Gofmt

    - -

    -Two minor details of the default formatting of Go source code have changed. -First, certain complex three-index slice expressions previously formatted like -x[i+1 : j:k] and now -format with more consistent spacing: x[i+1 : j : k]. -Second, single-method interface literals written on a single line, -which are sometimes used in type assertions, -are no longer split onto multiple lines. -

    - -

    -Note that these kinds of minor updates to gofmt are expected from time to time. -In general, we recommend against building systems that check that source code -matches the output of a specific version of gofmt. -For example, a continuous integration test that fails if any code already checked into -a repository is not “properly formatted” is inherently fragile and not recommended. -

    - -

    -If multiple programs must agree about which version of gofmt is used to format a source file, -we recommend that they do this by arranging to invoke the same gofmt binary. -For example, in the Go open source repository, our Git pre-commit hook is written in Go -and could import go/format directly, but instead it invokes the gofmt -binary found in the current path, so that the pre-commit hook need not be recompiled -each time gofmt changes. -

    - -

    Compiler Toolchain

    - -

    -The compiler includes many improvements to the performance of generated code, -spread fairly evenly across the supported architectures. -

    - -

    -The DWARF debug information recorded in binaries has been improved in a few ways: -constant values are now recorded; -line number information is more accurate, making source-level stepping through a program work better; -and each package is now presented as its own DWARF compilation unit. -

    - -

    -The various build modes -have been ported to more systems. -Specifically, c-shared now works on linux/ppc64le, windows/386, and windows/amd64; -pie now works on darwin/amd64 and also forces the use of external linking on all systems; -and plugin now works on linux/ppc64le and darwin/amd64. -

    - -

    -The linux/ppc64le port now requires the use of external linking -with any programs that use cgo, even uses by the standard library. -

    - -

    Assembler

    - -

    -For the ARM 32-bit port, the assembler now supports the instructions -BFC, -BFI, -BFX, -BFXU, -FMULAD, -FMULAF, -FMULSD, -FMULSF, -FNMULAD, -FNMULAF, -FNMULSD, -FNMULSF, -MULAD, -MULAF, -MULSD, -MULSF, -NMULAD, -NMULAF, -NMULD, -NMULF, -NMULSD, -NMULSF, -XTAB, -XTABU, -XTAH, -and -XTAHU. -

    - -

    -For the ARM 64-bit port, the assembler now supports the -VADD, -VADDP, -VADDV, -VAND, -VCMEQ, -VDUP, -VEOR, -VLD1, -VMOV, -VMOVI, -VMOVS, -VORR, -VREV32, -and -VST1 -instructions. -

    - -

    -For the PowerPC 64-bit port, the assembler now supports the POWER9 instructions -ADDEX, -CMPEQB, -COPY, -DARN, -LDMX, -MADDHD, -MADDHDU, -MADDLD, -MFVSRLD, -MTVSRDD, -MTVSRWS, -PASTECC, -VCMPNEZB, -VCMPNEZBCC, -and -VMSUMUDM. -

    - -

    -For the S390X port, the assembler now supports the -TMHH, -TMHL, -TMLH, -and -TMLL -instructions. -

    - -

    -For the X86 64-bit port, the assembler now supports 359 new instructions, -including the full AVX, AVX2, BMI, BMI2, F16C, FMA3, SSE2, SSE3, SSSE3, SSE4.1, and SSE4.2 extension sets. -The assembler also no longer implements MOVL $0, AX -as an XORL instruction, -to avoid clearing the condition flags unexpectedly. -

    - -

    Gccgo

    - -

    -Due to the alignment of Go's semiannual release schedule with GCC's -annual release schedule, -GCC release 7 contains the Go 1.8.3 version of gccgo. -We expect that the next release, GCC 8, will contain the Go 1.10 -version of gccgo. -

    - -

    Runtime

    - -

    -The behavior of nested calls to -LockOSThread and -UnlockOSThread -has changed. -These functions control whether a goroutine is locked to a specific operating system thread, -so that the goroutine only runs on that thread, and the thread only runs that goroutine. -Previously, calling LockOSThread more than once in a row -was equivalent to calling it once, and a single UnlockOSThread -always unlocked the thread. -Now, the calls nest: if LockOSThread is called multiple times, -UnlockOSThread must be called the same number of times -in order to unlock the thread. -Existing code that was careful not to nest these calls will remain correct. -Existing code that incorrectly assumed the calls nested will become correct. -Most uses of these functions in public Go source code falls into the second category. -

    - -

    -Because one common use of LockOSThread and UnlockOSThread -is to allow Go code to reliably modify thread-local state (for example, Linux or Plan 9 name spaces), -the runtime now treats locked threads as unsuitable for reuse or for creating new threads. -

    - -

    -Stack traces no longer include implicit wrapper functions (previously marked <autogenerated>), -unless a fault or panic happens in the wrapper itself. -As a result, skip counts passed to functions like Caller -should now always match the structure of the code as written, rather than depending on -optimization decisions and implementation details. -

    - -

    -The garbage collector has been modified to reduce its impact on allocation latency. -It now uses a smaller fraction of the overall CPU when running, but it may run more of the time. -The total CPU consumed by the garbage collector has not changed significantly. -

    - -

    -The GOROOT function -now defaults (when the $GOROOT environment variable is not set) -to the GOROOT or GOROOT_FINAL in effect -at the time the calling program was compiled. -Previously it used the GOROOT or GOROOT_FINAL in effect -at the time the toolchain that compiled the calling program was compiled. -

    - -

    -There is no longer a limit on the GOMAXPROCS setting. -(In Go 1.9 the limit was 1024.) -

    - -

    Performance

    - -

    -As always, the changes are so general and varied that precise -statements about performance are difficult to make. Most programs -should run a bit faster, due to speedups in the garbage collector, -better generated code, and optimizations in the core library. -

    - -

    Garbage Collector

    - -

    -Many applications should experience significantly lower allocation latency and overall performance overhead when the garbage collector is active. -

    - -

    Core library

    - -

    -All of the changes to the standard library are minor. -The changes in bytes -and net/url are the most likely to require updating of existing programs. -

    - -

    Minor changes to the library

    - -

    -As always, there are various minor changes and updates to the library, -made with the Go 1 promise of compatibility -in mind. -

    - -
    archive/tar
    -
    -

    -In general, the handling of special header formats is significantly improved and expanded. -

    -

    -FileInfoHeader has always -recorded the Unix UID and GID numbers from its os.FileInfo argument -(specifically, from the system-dependent information returned by the FileInfo's Sys method) -in the returned Header. -Now it also records the user and group names corresponding to those IDs, -as well as the major and minor device numbers for device files. -

    -

    -The new Header.Format field -of type Format -controls which tar header format the Writer uses. -The default, as before, is to select the most widely-supported header type -that can encode the fields needed by the header (USTAR if possible, or else PAX if possible, or else GNU). -The Reader sets Header.Format for each header it reads. -

    -

    -Reader and the Writer now support arbitrary PAX records, -using the new Header.PAXRecords field, -a generalization of the existing Xattrs field. -

    -

    -The Reader no longer insists that the file name or link name in GNU headers -be valid UTF-8. -

    -

    -When writing PAX- or GNU-format headers, the Writer now includes -the Header.AccessTime and Header.ChangeTime fields (if set). -When writing PAX-format headers, the times include sub-second precision. -

    -
    - -
    archive/zip
    -
    -

    -Go 1.10 adds more complete support for times and character set encodings in ZIP archives. -

    -

    -The original ZIP format used the standard MS-DOS encoding of year, month, day, hour, minute, and second into fields in two 16-bit values. -That encoding cannot represent time zones or odd seconds, so multiple extensions have been -introduced to allow richer encodings. -In Go 1.10, the Reader and Writer -now support the widely-understood Info-Zip extension that encodes the time separately in the 32-bit Unix “seconds since epoch” form. -The FileHeader's new Modified field of type time.Time -obsoletes the ModifiedTime and ModifiedDate fields, which continue to hold the MS-DOS encoding. -The Reader and Writer now adopt the common -convention that a ZIP archive storing a time zone-independent Unix time -also stores the local time in the MS-DOS field, -so that the time zone offset can be inferred. -For compatibility, the ModTime and -SetModTime methods -behave the same as in earlier releases; new code should use Modified directly. -

    -

    -The header for each file in a ZIP archive has a flag bit indicating whether -the name and comment fields are encoded as UTF-8, as opposed to a system-specific default encoding. -In Go 1.8 and earlier, the Writer never set the UTF-8 bit. -In Go 1.9, the Writer changed to set the UTF-8 bit almost always. -This broke the creation of ZIP archives containing Shift-JIS file names. -In Go 1.10, the Writer now sets the UTF-8 bit only when -both the name and the comment field are valid UTF-8 and at least one is non-ASCII. -Because non-ASCII encodings very rarely look like valid UTF-8, the new -heuristic should be correct nearly all the time. -Setting a FileHeader's new NonUTF8 field to true -disables the heuristic entirely for that file. -

    -

    -The Writer also now supports setting the end-of-central-directory record's comment field, -by calling the Writer's new SetComment method. -

    -
    - -
    bufio
    -
    -

    -The new Reader.Size -and Writer.Size -methods report the Reader or Writer's underlying buffer size. -

    -
    - -
    bytes
    -
    -

    -The -Fields, -FieldsFunc, -Split, -and -SplitAfter -functions have always returned subslices of their inputs. -Go 1.10 changes each returned subslice to have capacity equal to its length, -so that appending to one cannot overwrite adjacent data in the original input. -

    -
    - -
    crypto/cipher
    -
    -

    -NewOFB now panics if given -an initialization vector of incorrect length, like the other constructors in the -package always have. -(Previously it returned a nil Stream implementation.) -

    -
    - -
    crypto/tls
    -
    -

    -The TLS server now advertises support for SHA-512 signatures when using TLS 1.2. -The server already supported the signatures, but some clients would not select -them unless explicitly advertised. -

    -
    - -
    crypto/x509
    -
    -

    -Certificate.Verify -now enforces the name constraints for all -names contained in the certificate, not just the one name that a client has asked about. -Extended key usage restrictions are similarly now checked all at once. -As a result, after a certificate has been validated, now it can be trusted in its entirety. -It is no longer necessary to revalidate the certificate for each additional name -or key usage. -

    - -

    -Parsed certificates also now report URI names and IP, email, and URI constraints, using the new -Certificate fields -URIs, PermittedIPRanges, ExcludedIPRanges, -PermittedEmailAddresses, ExcludedEmailAddresses, -PermittedURIDomains, and ExcludedURIDomains. Certificates with -invalid values for those fields are now rejected. -

    - -

    -The new MarshalPKCS1PublicKey -and ParsePKCS1PublicKey -functions convert an RSA public key to and from PKCS#1-encoded form. -

    - -

    -The new MarshalPKCS8PrivateKey -function converts a private key to PKCS#8-encoded form. -(ParsePKCS8PrivateKey -has existed since Go 1.) -

    -
    - -
    crypto/x509/pkix
    -
    -

    -Name now implements a -String method that -formats the X.509 distinguished name in the standard RFC 2253 format. -

    -
    - -
    database/sql/driver
    -
    -

    -Drivers that currently hold on to the destination buffer provided by -driver.Rows.Next should ensure they no longer -write to a buffer assigned to the destination array outside of that call. -Drivers must be careful that underlying buffers are not modified when closing -driver.Rows. -

    -

    -Drivers that want to construct a sql.DB for -their clients can now implement the Connector interface -and call the new sql.OpenDB function, -instead of needing to encode all configuration into a string -passed to sql.Open. -

    -

    -Drivers that want to parse the configuration string only once per sql.DB -instead of once per sql.Conn, -or that want access to each sql.Conn's underlying context, -can make their Driver -implementations also implement DriverContext's -new OpenConnector method. -

    -

    -Drivers that implement ExecerContext -no longer need to implement Execer; -similarly, drivers that implement QueryerContext -no longer need to implement Queryer. -Previously, even if the context-based interfaces were implemented they were ignored -unless the non-context-based interfaces were also implemented. -

    -

    -To allow drivers to better isolate different clients using a cached driver connection in succession, -if a Conn implements the new -SessionResetter interface, -database/sql will now call ResetSession before -reusing the Conn for a new client. -

    -
    - -
    debug/elf
    -
    -

    -This release adds 348 new relocation constants divided between the relocation types -R_386, -R_AARCH64, -R_ARM, -R_PPC64, -and -R_X86_64. -

    -
    - -
    debug/macho
    -
    -

    -Go 1.10 adds support for reading relocations from Mach-O sections, -using the Section struct's new Relocs field -and the new Reloc, -RelocTypeARM, -RelocTypeARM64, -RelocTypeGeneric, -and -RelocTypeX86_64 -types and associated constants. -

    -

    -Go 1.10 also adds support for the LC_RPATH load command, -represented by the types -RpathCmd and -Rpath, -and new named constants -for the various flag bits found in headers. -

    -
    - -
    encoding/asn1
    -
    -

    -Marshal now correctly encodes -strings containing asterisks as type UTF8String instead of PrintableString, -unless the string is in a struct field with a tag forcing the use of PrintableString. -Marshal also now respects struct tags containing application directives. -

    -

    -The new MarshalWithParams -function marshals its argument as if the additional params were its associated -struct field tag. -

    -

    -Unmarshal now respects -struct field tags using the explicit and tag -directives. -

    -

    -Both Marshal and Unmarshal now support a new struct field tag -numeric, indicating an ASN.1 NumericString. -

    -
    - -
    encoding/csv
    -
    -

    -Reader now disallows the use of -nonsensical Comma and Comment settings, -such as NUL, carriage return, newline, invalid runes, and the Unicode replacement character, -or setting Comma and Comment equal to each other. -

    -

    -In the case of a syntax error in a CSV record that spans multiple input lines, Reader -now reports the line on which the record started in the ParseError's new StartLine field. -

    -
    - -
    encoding/hex
    -
    -

    -The new functions -NewEncoder -and -NewDecoder -provide streaming conversions to and from hexadecimal, -analogous to equivalent functions already in -encoding/base32 -and -encoding/base64. -

    - -

    -When the functions -Decode -and -DecodeString -encounter malformed input, -they now return the number of bytes already converted -along with the error. -Previously they always returned a count of 0 with any error. -

    -
    - -
    encoding/json
    -
    -

    -The Decoder -adds a new method -DisallowUnknownFields -that causes it to report inputs with unknown JSON fields as a decoding error. -(The default behavior has always been to discard unknown fields.) -

    - -

    -As a result of fixing a reflect bug, -Unmarshal -can no longer decode into fields inside -embedded pointers to unexported struct types, -because it cannot initialize the unexported embedded pointer -to point at fresh storage. -Unmarshal now returns an error in this case. -

    -
    - -
    encoding/pem
    -
    -

    -Encode -and -EncodeToMemory -no longer generate partial output when presented with a -block that is impossible to encode as PEM data. -

    -
    - -
    encoding/xml
    -
    -

    -The new function -NewTokenDecoder -is like -NewDecoder -but creates a decoder reading from a TokenReader -instead of an XML-formatted byte stream. -This is meant to enable the construction of XML stream transformers in client libraries. -

    -
    - -
    flag
    -
    -

    -The default -Usage function now prints -its first line of output to -CommandLine.Output() -instead of assuming os.Stderr, -so that the usage message is properly redirected for -clients using CommandLine.SetOutput. -

    -

    -PrintDefaults now -adds appropriate indentation after newlines in flag usage strings, -so that multi-line usage strings display nicely. -

    -

    -FlagSet adds new methods -ErrorHandling, -Name, -and -Output, -to retrieve the settings passed to -NewFlagSet -and -FlagSet.SetOutput. -

    -
    - -
    go/doc
    -
    -

    -To support the doc change described above, -functions returning slices of T, *T, **T, and so on -are now reported in T's Type's Funcs list, -instead of in the Package's Funcs list. -

    -
    - -
    go/importer
    -
    -

    -The For function now accepts a non-nil lookup argument. -

    -
    - -
    go/printer
    -
    -

    -The changes to the default formatting of Go source code -discussed in the gofmt section above -are implemented in the go/printer package -and also affect the output of the higher-level go/format package. -

    -
    - -
    hash
    -
    -

    -Implementations of the Hash interface are now -encouraged to implement encoding.BinaryMarshaler -and encoding.BinaryUnmarshaler -to allow saving and recreating their internal state, -and all implementations in the standard library -(hash/crc32, crypto/sha256, and so on) -now implement those interfaces. -

    -
    - -
    html/template
    -
    -

    -The new Srcset content -type allows for proper handling of values within the -srcset -attribute of img tags. -

    -
    - -
    math/big
    -
    -

    -Int now supports conversions to and from bases 2 through 62 -in its SetString and Text methods. -(Previously it only allowed bases 2 through 36.) -The value of the constant MaxBase has been updated. -

    -

    -Int adds a new -CmpAbs method -that is like Cmp but -compares only the absolute values (not the signs) of its arguments. -

    -

    -Float adds a new -Sqrt method to -compute square roots. -

    -
    - -
    math/cmplx
    -
    -

    -Branch cuts and other boundary cases in -Asin, -Asinh, -Atan, -and -Sqrt -have been corrected to match the definitions used in the C99 standard. -

    -
    - -
    math/rand
    -
    -

    -The new Shuffle function and corresponding -Rand.Shuffle method -shuffle an input sequence. -

    -
    - -
    math
    -
    -

    -The new functions -Round -and -RoundToEven -round their arguments to the nearest floating-point integer; -Round rounds a half-integer to its larger integer neighbor (away from zero) -while RoundToEven rounds a half-integer to its even integer neighbor. -

    - -

    -The new functions -Erfinv -and -Erfcinv -compute the inverse error function and the -inverse complementary error function. -

    -
    - -
    mime/multipart
    -
    -

    -Reader -now accepts parts with empty filename attributes. -

    -
    - -
    mime
    -
    -

    -ParseMediaType now discards -invalid attribute values; previously it returned those values as empty strings. -

    -
    - -
    net
    -
    -

    -The Conn and -Listener implementations -in this package now guarantee that when Close returns, -the underlying file descriptor has been closed. -(In earlier releases, if the Close stopped pending I/O -in other goroutines, the closing of the file descriptor could happen in one of those -goroutines shortly after Close returned.) -

    - -

    -TCPListener and -UnixListener -now implement -syscall.Conn, -to allow setting options on the underlying file descriptor -using syscall.RawConn.Control. -

    - -

    -The Conn implementations returned by Pipe -now support setting read and write deadlines. -

    - -

    -The IPConn.ReadMsgIP, -IPConn.WriteMsgIP, -UDPConn.ReadMsgUDP, -and -UDPConn.WriteMsgUDP, -methods are now implemented on Windows. -

    -
    - -
    net/http
    -
    -

    -On the client side, an HTTP proxy (most commonly configured by -ProxyFromEnvironment) -can now be specified as an https:// URL, -meaning that the client connects to the proxy over HTTPS before issuing a standard, proxied HTTP request. -(Previously, HTTP proxy URLs were required to begin with http:// or socks5://.) -

    -

    -On the server side, FileServer and its single-file equivalent ServeFile -now apply If-Range checks to HEAD requests. -FileServer also now reports directory read failures to the Server's ErrorLog. -The content-serving handlers also now omit the Content-Type header when serving zero-length content. -

    -

    -ResponseWriter's WriteHeader method now panics -if passed an invalid (non-3-digit) status code. -

    -

    - -The Server will no longer add an implicit Content-Type when a Handler does not write any output. -

    -

    -Redirect now sets the Content-Type header before writing its HTTP response. -

    -
    - -
    net/mail
    -
    -

    -ParseAddress and -ParseAddressList -now support a variety of obsolete address formats. -

    -
    - -
    net/smtp
    -
    -

    -The Client adds a new -Noop method, -to test whether the server is still responding. -It also now defends against possible SMTP injection in the inputs -to the Hello -and Verify methods. -

    -
    - -
    net/textproto
    -
    -

    -ReadMIMEHeader -now rejects any header that begins with a continuation (indented) header line. -Previously a header with an indented first line was treated as if the first line -were not indented. -

    -
    - -
    net/url
    -
    -

    -ResolveReference -now preserves multiple leading slashes in the target URL. -Previously it rewrote multiple leading slashes to a single slash, -which resulted in the http.Client -following certain redirects incorrectly. -

    -

    -For example, this code's output has changed: -

    -
    -base, _ := url.Parse("http://host//path//to/page1")
    -target, _ := url.Parse("page2")
    -fmt.Println(base.ResolveReference(target))
    -
    -

    -Note the doubled slashes around path. -In Go 1.9 and earlier, the resolved URL was http://host/path//to/page2: -the doubled slash before path was incorrectly rewritten -to a single slash, while the doubled slash after path was -correctly preserved. -Go 1.10 preserves both doubled slashes, resolving to http://host//path//to/page2 -as required by RFC 3986. -

    - -

    This change may break existing buggy programs that unintentionally -construct a base URL with a leading doubled slash in the path and inadvertently -depend on ResolveReference to correct that mistake. -For example, this can happen if code adds a host prefix -like http://host/ to a path like /my/api, -resulting in a URL with a doubled slash: http://host//my/api. -

    - -

    -UserInfo's methods -now treat a nil receiver as equivalent to a pointer to a zero UserInfo. -Previously, they panicked. -

    -
    - -
    os
    -
    -

    -File adds new methods -SetDeadline, -SetReadDeadline, -and -SetWriteDeadline -that allow setting I/O deadlines when the -underlying file descriptor supports non-blocking I/O operations. -The definition of these methods matches those in net.Conn. -If an I/O method fails due to missing a deadline, it will return a -timeout error; the -new IsTimeout function -reports whether an error represents a timeout. -

    - -

    -Also matching net.Conn, -File's -Close method -now guarantee that when Close returns, -the underlying file descriptor has been closed. -(In earlier releases, -if the Close stopped pending I/O -in other goroutines, the closing of the file descriptor could happen in one of those -goroutines shortly after Close returned.) -

    - -

    -On BSD, macOS, and Solaris systems, -Chtimes -now supports setting file times with nanosecond precision -(assuming the underlying file system can represent them). -

    -
    - -
    reflect
    -
    -

    -The Copy function now allows copying -from a string into a byte array or byte slice, to match the -built-in copy function. -

    - -

    -In structs, embedded pointers to unexported struct types were -previously incorrectly reported with an empty PkgPath -in the corresponding StructField, -with the result that for those fields, -and Value.CanSet -incorrectly returned true and -Value.Set -incorrectly succeeded. -The underlying metadata has been corrected; -for those fields, -CanSet now correctly returns false -and Set now correctly panics. -This may affect reflection-based unmarshalers -that could previously unmarshal into such fields -but no longer can. -For example, see the encoding/json notes. -

    -
    - -
    runtime/pprof
    -
    -

    -As noted above, the blocking and mutex profiles -now include symbol information so that they can be viewed without needing -the binary that generated them. -

    -
    - -
    strconv
    -
    -

    -ParseUint now returns -the maximum magnitude integer of the appropriate size -with any ErrRange error, as it was already documented to do. -Previously it returned 0 with ErrRange errors. -

    -
    - -
    strings
    -
    -

    -A new type -Builder is a replacement for -bytes.Buffer for the use case of -accumulating text into a string result. -The Builder's API is a restricted subset of bytes.Buffer's -that allows it to safely avoid making a duplicate copy of the data -during the String method. -

    -
    - -
    syscall
    -
    -

    -On Windows, -the new SysProcAttr field Token, -of type Token allows the creation of a process that -runs as another user during StartProcess -(and therefore also during os.StartProcess and -exec.Cmd.Start). -The new function CreateProcessAsUser -gives access to the underlying system call. -

    - -

    -On BSD, macOS, and Solaris systems, UtimesNano -is now implemented. -

    -
    - -
    time
    -
    -

    -LoadLocation now uses the directory -or uncompressed zip file named by the $ZONEINFO -environment variable before looking in the default system-specific list of -known installation locations or in $GOROOT/lib/time/zoneinfo.zip. -

    -

    -The new function LoadLocationFromTZData -allows conversion of IANA time zone file data to a Location. -

    -
    - -
    unicode
    -
    -

    -The unicode package and associated -support throughout the system has been upgraded from Unicode 9.0 to -Unicode 10.0, -which adds 8,518 new characters, including four new scripts, one new property, -a Bitcoin currency symbol, and 56 new emoji. -

    -
    diff --git a/doc/go1.11.html b/doc/go1.11.html deleted file mode 100644 index 483ecd872f..0000000000 --- a/doc/go1.11.html +++ /dev/null @@ -1,934 +0,0 @@ - - - - - - -

    Introduction to Go 1.11

    - -

    - The latest Go release, version 1.11, arrives six months after Go 1.10. - Most of its changes are in the implementation of the toolchain, runtime, and libraries. - As always, the release maintains the Go 1 promise of compatibility. - We expect almost all Go programs to continue to compile and run as before. -

    - -

    Changes to the language

    - -

    - There are no changes to the language specification. -

    - -

    Ports

    - -

    - As announced in the Go 1.10 release notes, Go 1.11 now requires - OpenBSD 6.2 or later, macOS 10.10 Yosemite or later, or Windows 7 or later; - support for previous versions of these operating systems has been removed. -

    - -

    - Go 1.11 supports the upcoming OpenBSD 6.4 release. Due to changes in - the OpenBSD kernel, older versions of Go will not work on OpenBSD 6.4. -

    - -

    - There are known issues with NetBSD on i386 hardware. -

    - -

    - The race detector is now supported on linux/ppc64le - and, to a lesser extent, on netbsd/amd64. The NetBSD race detector support - has known issues. -

    - -

    - The memory sanitizer (-msan) is now supported on linux/arm64. -

    - -

    - The build modes c-shared and c-archive are now supported on - freebsd/amd64. -

    - -

    - On 64-bit MIPS systems, the new environment variable settings - GOMIPS64=hardfloat (the default) and - GOMIPS64=softfloat select whether to use - hardware instructions or software emulation for floating-point computations. - For 32-bit systems, the environment variable is still GOMIPS, - as added in Go 1.10. -

    - -

    - On soft-float ARM systems (GOARM=5), Go now uses a more - efficient software floating point interface. This is transparent to - Go code, but ARM assembly that uses floating-point instructions not - guarded on GOARM will break and must be ported to - the new interface. -

    - -

    - Go 1.11 on ARMv7 no longer requires a Linux kernel configured - with KUSER_HELPERS. This setting is enabled in default - kernel configurations, but is sometimes disabled in stripped-down - configurations. -

    - -

    WebAssembly

    -

    - Go 1.11 adds an experimental port to WebAssembly - (js/wasm). -

    -

    - Go programs currently compile to one WebAssembly module that - includes the Go runtime for goroutine scheduling, garbage - collection, maps, etc. - As a result, the resulting size is at minimum around - 2 MB, or 500 KB compressed. Go programs can call into JavaScript - using the new experimental - syscall/js package. - Binary size and interop with other languages has not yet been a - priority but may be addressed in future releases. -

    -

    - As a result of the addition of the new GOOS value - "js" and GOARCH value "wasm", - Go files named *_js.go or *_wasm.go will - now be ignored by Go - tools except when those GOOS/GOARCH values are being used. - If you have existing filenames matching those patterns, you will need to rename them. -

    -

    - More information can be found on the - WebAssembly wiki page. -

    - -

    RISC-V GOARCH values reserved

    -

    - The main Go compiler does not yet support the RISC-V architecture - but we've reserved the GOARCH values - "riscv" and "riscv64", as used by Gccgo, - which does support RISC-V. This means that Go files - named *_riscv.go will now also - be ignored by Go - tools except when those GOOS/GOARCH values are being used. -

    - -

    Tools

    - -

    Modules, package versioning, and dependency management

    -

    - Go 1.11 adds preliminary support for a new concept called “modules,” - an alternative to GOPATH with integrated support for versioning and - package distribution. - Using modules, developers are no longer confined to working inside GOPATH, - version dependency information is explicit yet lightweight, - and builds are more reliable and reproducible. -

    - -

    - Module support is considered experimental. - Details are likely to change in response to feedback from Go 1.11 users, - and we have more tools planned. - Although the details of module support may change, projects that convert - to modules using Go 1.11 will continue to work with Go 1.12 and later. - If you encounter bugs using modules, - please file issues - so we can fix them. For more information, see the - go command documentation. -

    - -

    Import path restriction

    - -

    - Because Go module support assigns special meaning to the - @ symbol in command line operations, - the go command now disallows the use of - import paths containing @ symbols. - Such import paths were never allowed by go get, - so this restriction can only affect users building - custom GOPATH trees by other means. -

    - -

    Package loading

    - -

    - The new package - golang.org/x/tools/go/packages - provides a simple API for locating and loading packages of Go source code. - Although not yet part of the standard library, for many tasks it - effectively replaces the go/build - package, whose API is unable to fully support modules. - Because it runs an external query command such as - go list - to obtain information about Go packages, it enables the construction of - analysis tools that work equally well with alternative build systems - such as Bazel - and Buck. -

    - -

    Build cache requirement

    - -

    - Go 1.11 will be the last release to support setting the environment - variable GOCACHE=off to disable the - build cache, - introduced in Go 1.10. - Starting in Go 1.12, the build cache will be required, - as a step toward eliminating $GOPATH/pkg. - The module and package loading support described above - already require that the build cache be enabled. - If you have disabled the build cache to avoid problems you encountered, - please file an issue to let us know about them. -

    - -

    Compiler toolchain

    - -

    - More functions are now eligible for inlining by default, including - functions that call panic. -

    - -

    - The compiler toolchain now supports column information - in line - directives. -

    - -

    - A new package export data format has been introduced. - This should be transparent to end users, except for speeding up - build times for large Go projects. - If it does cause problems, it can be turned off again by - passing -gcflags=all=-iexport=false to - the go tool when building a binary. -

    - -

    - The compiler now rejects unused variables declared in a type switch - guard, such as x in the following example: -

    -
    -func f(v interface{}) {
    -	switch x := v.(type) {
    -	}
    -}
    -
    -

    - This was already rejected by both gccgo - and go/types. -

    - -

    Assembler

    - -

    - The assembler for amd64 now accepts AVX512 instructions. -

    - -

    Debugging

    - -

    - The compiler now produces significantly more accurate debug - information for optimized binaries, including variable location - information, line numbers, and breakpoint locations. - - This should make it possible to debug binaries - compiled without -N -l. - - There are still limitations to the quality of the debug information, - some of which are fundamental, and some of which will continue to - improve with future releases. -

    - -

    - DWARF sections are now compressed by default because of the expanded - and more accurate debug information produced by the compiler. - - This is transparent to most ELF tools (such as debuggers on Linux - and *BSD) and is supported by the Delve debugger on all platforms, - but has limited support in the native tools on macOS and Windows. - - To disable DWARF compression, - pass -ldflags=-compressdwarf=false to - the go tool when building a binary. -

    - -

    - Go 1.11 adds experimental support for calling Go functions from - within a debugger. - - This is useful, for example, to call String methods - when paused at a breakpoint. - - This is currently only supported by Delve (version 1.1.0 and up). -

    - -

    Test

    - -

    - Since Go 1.10, the go test command runs - go vet on the package being tested, - to identify problems before running the test. Since vet - typechecks the code with go/types - before running, tests that do not typecheck will now fail. - - In particular, tests that contain an unused variable inside a - closure compiled with Go 1.10, because the Go compiler incorrectly - accepted them (Issue #3059), - but will now fail, since go/types correctly reports an - "unused variable" error in this case. -

    - -

    - The -memprofile flag - to go test now defaults to the - "allocs" profile, which records the total bytes allocated since the - test began (including garbage-collected bytes). -

    - -

    Vet

    - -

    - The go vet - command now reports a fatal error when the package under analysis - does not typecheck. Previously, a type checking error simply caused - a warning to be printed, and vet to exit with status 1. -

    - -

    - Additionally, go vet - has become more robust when format-checking printf wrappers. - Vet now detects the mistake in this example: -

    - -
    -func wrapper(s string, args ...interface{}) {
    -	fmt.Printf(s, args...)
    -}
    -
    -func main() {
    -	wrapper("%s", 42)
    -}
    -
    - -

    Trace

    - -

    - With the new runtime/trace - package's user - annotation API, users can record application-level information - in execution traces and create groups of related goroutines. - The go tool trace - command visualizes this information in the trace view and the new - user task/region analysis page. -

    - -

    Cgo

    - -

    -Since Go 1.10, cgo has translated some C pointer types to the Go -type uintptr. These types include -the CFTypeRef hierarchy in Darwin's CoreFoundation -framework and the jobject hierarchy in Java's JNI -interface. In Go 1.11, several improvements have been made to the code -that detects these types. Code that uses these types may need some -updating. See the Go 1.10 release notes for -details. -

    - -

    Go command

    - -

    - The environment variable GOFLAGS may now be used - to set default flags for the go command. - This is useful in certain situations. - Linking can be noticeably slower on underpowered systems due to DWARF, - and users may want to set -ldflags=-w by default. - For modules, some users and CI systems will want vendoring always, - so they should set -mod=vendor by default. - For more information, see the go - command documentation. -

    - -

    Godoc

    - -

    - Go 1.11 will be the last release to support godoc's command-line interface. - In future releases, godoc will only be a web server. Users should use - go doc for command-line help output instead. -

    - -

    - The godoc web server now shows which version of Go introduced - new API features. The initial Go version of types, funcs, and methods are shown - right-aligned. For example, see UserCacheDir, with "1.11" - on the right side. For struct fields, inline comments are added when the struct field was - added in a Go version other than when the type itself was introduced. - For a struct field example, see - ClientTrace.Got1xxResponse. -

    - -

    Gofmt

    - -

    - One minor detail of the default formatting of Go source code has changed. - When formatting expression lists with inline comments, the comments were - aligned according to a heuristic. - However, in some cases the alignment would be split up too easily, or - introduce too much whitespace. - The heuristic has been changed to behave better for human-written code. -

    - -

    - Note that these kinds of minor updates to gofmt are expected from time to - time. - In general, systems that need consistent formatting of Go source code should - use a specific version of the gofmt binary. - See the go/format package documentation for more - information. -

    - -

    Run

    - -

    - - The go run - command now allows a single import path, a directory name or a - pattern matching a single package. - This allows go run pkg or go run dir, most importantly go run . -

    - -

    Runtime

    - -

    - The runtime now uses a sparse heap layout so there is no longer a - limit to the size of the Go heap (previously, the limit was 512GiB). - This also fixes rare "address space conflict" failures in mixed Go/C - binaries or binaries compiled with -race. -

    - -

    - On macOS and iOS, the runtime now uses libSystem.dylib instead of - calling the kernel directly. This should make Go binaries more - compatible with future versions of macOS and iOS. - The syscall package still makes direct - system calls; fixing this is planned for a future release. -

    - -

    Performance

    - -

    -As always, the changes are so general and varied that precise -statements about performance are difficult to make. Most programs -should run a bit faster, due to better generated code and -optimizations in the core library. -

    - -

    -There were multiple performance changes to the math/big -package as well as many changes across the tree specific to GOARCH=arm64. -

    - -

    Compiler toolchain

    - -

    - The compiler now optimizes map clearing operations of the form: -

    -
    -for k := range m {
    -	delete(m, k)
    -}
    -
    - -

    - The compiler now optimizes slice extension of the form - append(s, make([]T, n)...). -

    - -

    - The compiler now performs significantly more aggressive bounds-check - and branch elimination. Notably, it now recognizes transitive - relations, so if i<j and j<len(s), - it can use these facts to eliminate the bounds check - for s[i]. It also understands simple arithmetic such - as s[i-10] and can recognize more inductive cases in - loops. Furthermore, the compiler now uses bounds information to more - aggressively optimize shift operations. -

    - -

    Core library

    - -

    - All of the changes to the standard library are minor. -

    - -

    Minor changes to the library

    - -

    - As always, there are various minor changes and updates to the library, - made with the Go 1 promise of compatibility - in mind. -

    - - - - - - -
    crypto
    -
    -

    - Certain crypto operations, including - ecdsa.Sign, - rsa.EncryptPKCS1v15 and - rsa.GenerateKey, - now randomly read an extra byte of randomness to ensure tests don't rely on internal behavior. -

    - -
    - -
    crypto/cipher
    -
    -

    - The new function NewGCMWithTagSize - implements Galois Counter Mode with non-standard tag lengths for compatibility with existing cryptosystems. -

    - -
    - -
    crypto/rsa
    -
    -

    - PublicKey now implements a - Size method that - returns the modulus size in bytes. -

    - -
    - -
    crypto/tls
    -
    -

    - ConnectionState's new - ExportKeyingMaterial - method allows exporting keying material bound to the - connection according to RFC 5705. -

    - -
    - -
    crypto/x509
    -
    -

    - The deprecated, legacy behavior of treating the CommonName field as - a hostname when no Subject Alternative Names are present is now disabled when the CN is not a - valid hostname. - The CommonName can be completely ignored by adding the experimental value - x509ignoreCN=1 to the GODEBUG environment variable. - When the CN is ignored, certificates without SANs validate under chains with name constraints - instead of returning NameConstraintsWithoutSANs. -

    - -

    - Extended key usage restrictions are again checked only if they appear in the KeyUsages - field of VerifyOptions, instead of always being checked. - This matches the behavior of Go 1.9 and earlier. -

    - -

    - The value returned by SystemCertPool - is now cached and might not reflect system changes between invocations. -

    - -
    - -
    debug/elf
    -
    -

    - More ELFOSABI - and EM - constants have been added. -

    - -
    - -
    encoding/asn1
    -
    -

    - Marshal and Unmarshal - now support "private" class annotations for fields. -

    - -
    - -
    encoding/base32
    -
    -

    - The decoder now consistently - returns io.ErrUnexpectedEOF for an incomplete - chunk. Previously it would return io.EOF in some - cases. -

    - -
    - -
    encoding/csv
    -
    -

    - The Reader now rejects attempts to set - the Comma - field to a double-quote character, as double-quote characters - already have a special meaning in CSV. -

    - -
    - - - -
    html/template
    -
    -

    - The package has changed its behavior when a typed interface - value is passed to an implicit escaper function. Previously such - a value was written out as (an escaped form) - of <nil>. Now such values are ignored, just - as an untyped nil value is (and always has been) - ignored. -

    - -
    - -
    image/gif
    -
    -

    - Non-looping animated GIFs are now supported. They are denoted by having a - LoopCount of -1. -

    - -
    - -
    io/ioutil
    -
    -

    - The TempFile - function now supports specifying where the random characters in - the filename are placed. If the prefix argument - includes a "*", the random string replaces the - "*". For example, a prefix argument of "myname.*.bat" will - result in a random filename such as - "myname.123456.bat". If no "*" is - included the old behavior is retained, and the random digits are - appended to the end. -

    - -
    - -
    math/big
    -
    - -

    - ModInverse now returns nil when g and n are not relatively prime. The result was previously undefined. -

    - -
    - -
    mime/multipart
    -
    -

    - The handling of form-data with missing/empty file names has been - restored to the behavior in Go 1.9: in the - Form for - the form-data part the value is available in - the Value field rather than the File - field. In Go releases 1.10 through 1.10.3 a form-data part with - a missing/empty file name and a non-empty "Content-Type" field - was stored in the File field. This change was a - mistake in 1.10 and has been reverted to the 1.9 behavior. -

    - -
    - -
    mime/quotedprintable
    -
    -

    - To support invalid input found in the wild, the package now - permits non-ASCII bytes but does not validate their encoding. -

    - -
    - -
    net
    -
    -

    - The new ListenConfig type and the new - Dialer.Control field permit - setting socket options before accepting and creating connections, respectively. -

    - -

    - The syscall.RawConn Read - and Write methods now work correctly on Windows. -

    - -

    - The net package now automatically uses the - splice system call - on Linux when copying data between TCP connections in - TCPConn.ReadFrom, as called by - io.Copy. The result is faster, more efficient TCP proxying. -

    - -

    - The TCPConn.File, - UDPConn.File, - UnixConn.File, - and IPConn.File - methods no longer put the returned *os.File into - blocking mode. -

    - -
    - -
    net/http
    -
    -

    - The Transport type has a - new MaxConnsPerHost - option that permits limiting the maximum number of connections - per host. -

    - -

    - The Cookie type has a new - SameSite field - (of new type also named - SameSite) to represent the new cookie attribute recently supported by most browsers. - The net/http's Transport does not use the SameSite - attribute itself, but the package supports parsing and serializing the - attribute for browsers to use. -

    - -

    - It is no longer allowed to reuse a Server - after a call to - Shutdown or - Close. It was never officially supported - in the past and had often surprising behavior. Now, all future calls to the server's Serve - methods will return errors after a shutdown or close. -

    - - - -

    - The constant StatusMisdirectedRequest is now defined for HTTP status code 421. -

    - -

    - The HTTP server will no longer cancel contexts or send on - CloseNotifier - channels upon receiving pipelined HTTP/1.1 requests. Browsers do - not use HTTP pipelining, but some clients (such as - Debian's apt) may be configured to do so. -

    - -

    - ProxyFromEnvironment, which is used by the - DefaultTransport, now - supports CIDR notation and ports in the NO_PROXY environment variable. -

    - -
    - -
    net/http/httputil
    -
    -

    - The - ReverseProxy - has a new - ErrorHandler - option to permit changing how errors are handled. -

    - -

    - The ReverseProxy now also passes - "TE: trailers" request headers - through to the backend, as required by the gRPC protocol. -

    - -
    - -
    os
    -
    -

    - The new UserCacheDir function - returns the default root directory to use for user-specific cached data. -

    - -

    - The new ModeIrregular - is a FileMode bit to represent - that a file is not a regular file, but nothing else is known about it, or that - it's not a socket, device, named pipe, symlink, or other file type for which - Go has a defined mode bit. -

    - -

    - Symlink now works - for unprivileged users on Windows 10 on machines with Developer - Mode enabled. -

    - -

    - When a non-blocking descriptor is passed - to NewFile, the - resulting *File will be kept in non-blocking - mode. This means that I/O for that *File will use - the runtime poller rather than a separate thread, and that - the SetDeadline - methods will work. -

    - -
    - -
    os/signal
    -
    -

    - The new Ignored function reports - whether a signal is currently ignored. -

    - -
    - -
    os/user
    -
    -

    - The os/user package can now be built in pure Go - mode using the build tag "osusergo", - independent of the use of the environment - variable CGO_ENABLED=0. Previously the only way to use - the package's pure Go implementation was to disable cgo - support across the entire program. -

    - -
    - - - -
    runtime
    -
    - -

    - Setting the GODEBUG=tracebackancestors=N - environment variable now extends tracebacks with the stacks at - which goroutines were created, where N limits the - number of ancestor goroutines to report. -

    - -
    - -
    runtime/pprof
    -
    -

    - This release adds a new "allocs" profile type that profiles - total number of bytes allocated since the program began - (including garbage-collected bytes). This is identical to the - existing "heap" profile viewed in -alloc_space mode. - Now go test -memprofile=... reports an "allocs" profile - instead of "heap" profile. -

    - -
    - -
    sync
    -
    -

    - The mutex profile now includes reader/writer contention - for RWMutex. - Writer/writer contention was already included in the mutex - profile. -

    - -
    - -
    syscall
    -
    -

    - On Windows, several fields were changed from uintptr to a new - Pointer - type to avoid problems with Go's garbage collector. The same change was made - to the golang.org/x/sys/windows - package. For any code affected, users should first migrate away from the syscall - package to the golang.org/x/sys/windows package, and then change - to using the Pointer, while obeying the - unsafe.Pointer conversion rules. -

    - -

    - On Linux, the flags parameter to - Faccessat - is now implemented just as in glibc. In earlier Go releases the - flags parameter was ignored. -

    - -

    - On Linux, the flags parameter to - Fchmodat - is now validated. Linux's fchmodat doesn't support the flags parameter - so we now mimic glibc's behavior and return an error if it's non-zero. -

    - -
    - -
    text/scanner
    -
    -

    - The Scanner.Scan method now returns - the RawString token - instead of String - for raw string literals. -

    - -
    - -
    text/template
    -
    -

    - Modifying template variables via assignments is now permitted via the = token: -

    -
    -  {{"{{"}} $v := "init" {{"}}"}}
    -  {{"{{"}} if true {{"}}"}}
    -    {{"{{"}} $v = "changed" {{"}}"}}
    -  {{"{{"}} end {{"}}"}}
    -  v: {{"{{"}} $v {{"}}"}} {{"{{"}}/* "changed" */{{"}}"}}
    - -

    - In previous versions untyped nil values passed to - template functions were ignored. They are now passed as normal - arguments. -

    - -
    - -
    time
    -
    -

    - Parsing of timezones denoted by sign and offset is now - supported. In previous versions, numeric timezone names - (such as +03) were not considered valid, and only - three-letter abbreviations (such as MST) were accepted - when expecting a timezone name. -

    -
    diff --git a/doc/go1.12.html b/doc/go1.12.html deleted file mode 100644 index a8b0c87fe5..0000000000 --- a/doc/go1.12.html +++ /dev/null @@ -1,949 +0,0 @@ - - - - - - -

    Introduction to Go 1.12

    - -

    - The latest Go release, version 1.12, arrives six months after Go 1.11. - Most of its changes are in the implementation of the toolchain, runtime, and libraries. - As always, the release maintains the Go 1 promise of compatibility. - We expect almost all Go programs to continue to compile and run as before. -

    - -

    Changes to the language

    - -

    - There are no changes to the language specification. -

    - -

    Ports

    - -

    - The race detector is now supported on linux/arm64. -

    - -

    - Go 1.12 is the last release that is supported on FreeBSD 10.x, which has - already reached end-of-life. Go 1.13 will require FreeBSD 11.2+ or FreeBSD - 12.0+. - FreeBSD 12.0+ requires a kernel with the COMPAT_FREEBSD11 option set (this is the default). -

    - -

    - cgo is now supported on linux/ppc64. -

    - -

    - hurd is now a recognized value for GOOS, reserved - for the GNU/Hurd system for use with gccgo. -

    - -

    Windows

    - -

    - Go's new windows/arm port supports running Go on Windows 10 - IoT Core on 32-bit ARM chips such as the Raspberry Pi 3. -

    - -

    AIX

    - -

    - Go now supports AIX 7.2 and later on POWER8 architectures (aix/ppc64). External linking, cgo, pprof and the race detector aren't yet supported. -

    - -

    Darwin

    - -

    - Go 1.12 is the last release that will run on macOS 10.10 Yosemite. - Go 1.13 will require macOS 10.11 El Capitan or later. -

    - -

    - libSystem is now used when making syscalls on Darwin, - ensuring forward-compatibility with future versions of macOS and iOS. - - The switch to libSystem triggered additional App Store - checks for private API usage. Since it is considered private, - syscall.Getdirentries now always fails with - ENOSYS on iOS. - Additionally, syscall.Setrlimit - reports invalid argument in places where it historically - succeeded. These consequences are not specific to Go and users should expect - behavioral parity with libSystem's implementation going forward. -

    - -

    Tools

    - -

    go tool vet no longer supported

    - -

    - The go vet command has been rewritten to serve as the - base for a range of different source code analysis tools. See - the golang.org/x/tools/go/analysis - package for details. A side-effect is that go tool vet - is no longer supported. External tools that use go tool - vet must be changed to use go - vet. Using go vet instead of go tool - vet should work with all supported versions of Go. -

    - -

    - As part of this change, the experimental -shadow option - is no longer available with go vet. Checking for - variable shadowing may now be done using -

    -go get -u golang.org/x/tools/go/analysis/passes/shadow/cmd/shadow
    -go vet -vettool=$(which shadow)
    -
    -

    - -

    Tour

    - -

    -The Go tour is no longer included in the main binary distribution. To -run the tour locally, instead of running go tool tour, -manually install it: -

    -go get -u golang.org/x/tour
    -tour
    -
    -

    - -

    Build cache requirement

    - -

    - The build cache is now - required as a step toward eliminating - $GOPATH/pkg. Setting the environment variable - GOCACHE=off will cause go commands that write to the - cache to fail. -

    - -

    Binary-only packages

    - -

    - Go 1.12 is the last release that will support binary-only packages. -

    - -

    Cgo

    - -

    - Go 1.12 will translate the C type EGLDisplay to the Go type uintptr. - This change is similar to how Go 1.10 and newer treats Darwin's CoreFoundation - and Java's JNI types. See the - cgo documentation - for more information. -

    - -

    - Mangled C names are no longer accepted in packages that use Cgo. Use the Cgo - names instead. For example, use the documented cgo name C.char - rather than the mangled name _Ctype_char that cgo generates. -

    - -

    Modules

    - -

    - When GO111MODULE is set to on, the go - command now supports module-aware operations outside of a module directory, - provided that those operations do not need to resolve import paths relative to - the current directory or explicitly edit the go.mod file. - Commands such as go get, - go list, and - go mod download behave as if in a - module with initially-empty requirements. - In this mode, go env GOMOD reports - the system's null device (/dev/null or NUL). -

    - -

    - go commands that download and extract modules are now safe to - invoke concurrently. - The module cache (GOPATH/pkg/mod) must reside in a filesystem that - supports file locking. -

    - -

    - The go directive in a go.mod file now indicates the - version of the language used by the files within that module. - It will be set to the current release - (go 1.12) if no existing version is - present. - If the go directive for a module specifies a - version newer than the toolchain in use, the go command - will attempt to build the packages regardless, and will note the mismatch only if - that build fails. -

    - -

    - This changed use of the go directive means that if you - use Go 1.12 to build a module, thus recording go 1.12 - in the go.mod file, you will get an error when - attempting to build the same module with Go 1.11 through Go 1.11.3. - Go 1.11.4 or later will work fine, as will releases older than Go 1.11. - If you must use Go 1.11 through 1.11.3, you can avoid the problem by - setting the language version to 1.11, using the Go 1.12 go tool, - via go mod edit -go=1.11. -

    - -

    - When an import cannot be resolved using the active modules, - the go command will now try to use the modules mentioned in the - main module's replace directives before consulting the module - cache and the usual network sources. - If a matching replacement is found but the replace directive does - not specify a version, the go command uses a pseudo-version - derived from the zero time.Time (such - as v0.0.0-00010101000000-000000000000). -

    - -

    Compiler toolchain

    - -

    - The compiler's live variable analysis has improved. This may mean that - finalizers will be executed sooner in this release than in previous - releases. If that is a problem, consider the appropriate addition of a - runtime.KeepAlive call. -

    - -

    - More functions are now eligible for inlining by default, including - functions that do nothing but call another function. - This extra inlining makes it additionally important to use - runtime.CallersFrames - instead of iterating over the result of - runtime.Callers directly. -

    -// Old code which no longer works correctly (it will miss inlined call frames).
    -var pcs [10]uintptr
    -n := runtime.Callers(1, pcs[:])
    -for _, pc := range pcs[:n] {
    -	f := runtime.FuncForPC(pc)
    -	if f != nil {
    -		fmt.Println(f.Name())
    -	}
    -}
    -
    -
    -// New code which will work correctly.
    -var pcs [10]uintptr
    -n := runtime.Callers(1, pcs[:])
    -frames := runtime.CallersFrames(pcs[:n])
    -for {
    -	frame, more := frames.Next()
    -	fmt.Println(frame.Function)
    -	if !more {
    -		break
    -	}
    -}
    -
    -

    - -

    - Wrappers generated by the compiler to implement method expressions - are no longer reported - by runtime.CallersFrames - and runtime.Stack. They - are also not printed in panic stack traces. - - This change aligns the gc toolchain to match - the gccgo toolchain, which already elided such wrappers - from stack traces. - - Clients of these APIs might need to adjust for the missing - frames. For code that must interoperate between 1.11 and 1.12 - releases, you can replace the method expression x.M - with the function literal func (...) { x.M(...) } . -

    - -

    - The compiler now accepts a -lang flag to set the Go language - version to use. For example, -lang=go1.8 causes the compiler to - emit an error if the program uses type aliases, which were added in Go 1.9. - Language changes made before Go 1.12 are not consistently enforced. -

    - -

    - The compiler toolchain now uses different conventions to call Go - functions and assembly functions. This should be invisible to users, - except for calls that simultaneously cross between Go and - assembly and cross a package boundary. If linking results - in an error like "relocation target not defined for ABIInternal (but - is defined for ABI0)", please refer to the - compatibility section - of the ABI design document. -

    - -

    - There have been many improvements to the DWARF debug information - produced by the compiler, including improvements to argument - printing and variable location information. -

    - -

    - Go programs now also maintain stack frame pointers on linux/arm64 - for the benefit of profiling tools like perf. The frame pointer - maintenance has a small run-time overhead that varies but averages around 3%. - To build a toolchain that does not use frame pointers, set - GOEXPERIMENT=noframepointer when running make.bash. -

    - -

    - The obsolete "safe" compiler mode (enabled by the -u gcflag) has been removed. -

    - -

    godoc and go doc

    - -

    - In Go 1.12, godoc no longer has a command-line interface and - is only a web server. Users should use go doc - for command-line help output instead. Go 1.12 is the last release that will - include the godoc webserver; in Go 1.13 it will be available - via go get. -

    - -

    - go doc now supports the -all flag, - which will cause it to print all exported APIs and their documentation, - as the godoc command line used to do. -

    - -

    - go doc also now includes the -src flag, - which will show the target's source code. -

    - -

    Trace

    - -

    - The trace tool now supports plotting mutator utilization curves, - including cross-references to the execution trace. These are useful - for analyzing the impact of the garbage collector on application - latency and throughput. -

    - -

    Assembler

    - -

    - On arm64, the platform register was renamed from - R18 to R18_PLATFORM to prevent accidental - use, as the OS could choose to reserve this register. -

    - -

    Runtime

    - -

    - Go 1.12 significantly improves the performance of sweeping when a - large fraction of the heap remains live. This reduces allocation - latency immediately following a garbage collection. -

    - -

    - The Go runtime now releases memory back to the operating system more - aggressively, particularly in response to large allocations that - can't reuse existing heap space. -

    - -

    - The Go runtime's timer and deadline code is faster and scales better - with higher numbers of CPUs. In particular, this improves the - performance of manipulating network connection deadlines. -

    - -

    - On Linux, the runtime now uses MADV_FREE to release unused - memory. This is more efficient but may result in higher reported - RSS. The kernel will reclaim the unused data when it is needed. - To revert to the Go 1.11 behavior (MADV_DONTNEED), set the - environment variable GODEBUG=madvdontneed=1. -

    - -

    - Adding cpu.extension=off to the - GODEBUG environment - variable now disables the use of optional CPU instruction - set extensions in the standard library and runtime. This is not - yet supported on Windows. -

    - -

    - Go 1.12 improves the accuracy of memory profiles by fixing - overcounting of large heap allocations. -

    - -

    - Tracebacks, runtime.Caller, - and runtime.Callers no longer include - compiler-generated initialization functions. Doing a traceback - during the initialization of a global variable will now show a - function named PKG.init.ializers. -

    - -

    Core library

    - -

    TLS 1.3

    - -

    - Go 1.12 adds opt-in support for TLS 1.3 in the crypto/tls package as - specified by RFC 8446. It can - be enabled by adding the value tls13=1 to the GODEBUG - environment variable. It will be enabled by default in Go 1.13. -

    - -

    - To negotiate TLS 1.3, make sure you do not set an explicit MaxVersion in - Config and run your program with - the environment variable GODEBUG=tls13=1 set. -

    - -

    - All TLS 1.2 features except TLSUnique in - ConnectionState - and renegotiation are available in TLS 1.3 and provide equivalent or - better security and performance. Note that even though TLS 1.3 is backwards - compatible with previous versions, certain legacy systems might not work - correctly when attempting to negotiate it. RSA certificate keys too small - to be secure (including 512-bit keys) will not work with TLS 1.3. -

    - -

    - TLS 1.3 cipher suites are not configurable. All supported cipher suites are - safe, and if PreferServerCipherSuites is set in - Config the preference order - is based on the available hardware. -

    - -

    - Early data (also called "0-RTT mode") is not currently supported as a - client or server. Additionally, a Go 1.12 server does not support skipping - unexpected early data if a client sends it. Since TLS 1.3 0-RTT mode - involves clients keeping state regarding which servers support 0-RTT, - a Go 1.12 server cannot be part of a load-balancing pool where some other - servers do support 0-RTT. If switching a domain from a server that supported - 0-RTT to a Go 1.12 server, 0-RTT would have to be disabled for at least the - lifetime of the issued session tickets before the switch to ensure - uninterrupted operation. -

    - -

    - In TLS 1.3 the client is the last one to speak in the handshake, so if it causes - an error to occur on the server, it will be returned on the client by the first - Read, not by - Handshake. For - example, that will be the case if the server rejects the client certificate. - Similarly, session tickets are now post-handshake messages, so are only - received by the client upon its first - Read. -

    - -

    Minor changes to the library

    - -

    - As always, there are various minor changes and updates to the library, - made with the Go 1 promise of compatibility - in mind. -

    - - - -
    bufio
    -
    -

    - Reader's UnreadRune and - UnreadByte methods will now return an error - if they are called after Peek. -

    - -
    - -
    bytes
    -
    -

    - The new function ReplaceAll returns a copy of - a byte slice with all non-overlapping instances of a value replaced by another. -

    - -

    - A pointer to a zero-value Reader is now - functionally equivalent to NewReader(nil). - Prior to Go 1.12, the former could not be used as a substitute for the latter in all cases. -

    - -
    - -
    crypto/rand
    -
    -

    - A warning will now be printed to standard error the first time - Reader.Read is blocked for more than 60 seconds waiting - to read entropy from the kernel. -

    - -

    - On FreeBSD, Reader now uses the getrandom - system call if available, /dev/urandom otherwise. -

    - -
    - -
    crypto/rc4
    -
    -

    - This release removes the assembly implementations, leaving only - the pure Go version. The Go compiler generates code that is - either slightly better or slightly worse, depending on the exact - CPU. RC4 is insecure and should only be used for compatibility - with legacy systems. -

    - -
    - -
    crypto/tls
    -
    -

    - If a client sends an initial message that does not look like TLS, the server - will no longer reply with an alert, and it will expose the underlying - net.Conn in the new field Conn of - RecordHeaderError. -

    - -
    - -
    database/sql
    -
    -

    - A query cursor can now be obtained by passing a - *Rows - value to the Row.Scan method. -

    - -
    - -
    expvar
    -
    -

    - The new Delete method allows - for deletion of key/value pairs from a Map. -

    - -
    - -
    fmt
    -
    -

    - Maps are now printed in key-sorted order to ease testing. The ordering rules are: -

      -
    • When applicable, nil compares low -
    • ints, floats, and strings order by < -
    • NaN compares less than non-NaN floats -
    • bool compares false before true -
    • Complex compares real, then imaginary -
    • Pointers compare by machine address -
    • Channel values compare by machine address -
    • Structs compare each field in turn -
    • Arrays compare each element in turn -
    • Interface values compare first by reflect.Type describing the concrete type - and then by concrete value as described in the previous rules. -
    -

    - -

    - When printing maps, non-reflexive key values like NaN were previously - displayed as <nil>. As of this release, the correct values are printed. -

    - -
    - -
    go/doc
    -
    -

    - To address some outstanding issues in cmd/doc, - this package has a new Mode bit, - PreserveAST, which controls whether AST data is cleared. -

    - -
    - -
    go/token
    -
    -

    - The File type has a new - LineStart field, - which returns the position of the start of a given line. This is especially useful - in programs that occasionally handle non-Go files, such as assembly, but wish to use - the token.Pos mechanism to identify file positions. -

    - -
    - -
    image
    -
    -

    - The RegisterFormat function is now safe for concurrent use. -

    - -
    - -
    image/png
    -
    -

    - Paletted images with fewer than 16 colors now encode to smaller outputs. -

    - -
    - -
    io
    -
    -

    - The new StringWriter interface wraps the - WriteString function. -

    - -
    - -
    math
    -
    -

    - The functions - Sin, - Cos, - Tan, - and Sincos now - apply Payne-Hanek range reduction to huge arguments. This - produces more accurate answers, but they will not be bit-for-bit - identical with the results in earlier releases. -

    -
    - -
    math/bits
    -
    -

    - New extended precision operations Add, Sub, Mul, and Div are available in uint, uint32, and uint64 versions. -

    - -
    - -
    net
    -
    -

    - The - Dialer.DualStack setting is now ignored and deprecated; - RFC 6555 Fast Fallback ("Happy Eyeballs") is now enabled by default. To disable, set - Dialer.FallbackDelay to a negative value. -

    - -

    - Similarly, TCP keep-alives are now enabled by default if - Dialer.KeepAlive is zero. - To disable, set it to a negative value. -

    - -

    - On Linux, the splice system call is now used when copying from a - UnixConn to a - TCPConn. -

    -
    - -
    net/http
    -
    -

    - The HTTP server now rejects misdirected HTTP requests to HTTPS servers with a plaintext "400 Bad Request" response. -

    - -

    - The new Client.CloseIdleConnections - method calls the Client's underlying Transport's CloseIdleConnections - if it has one. -

    - -

    - The Transport no longer rejects HTTP responses which declare - HTTP Trailers but don't use chunked encoding. Instead, the declared trailers are now just ignored. -

    - -

    - The Transport no longer handles MAX_CONCURRENT_STREAMS values - advertised from HTTP/2 servers as strictly as it did during Go 1.10 and Go 1.11. The default behavior is now back - to how it was in Go 1.9: each connection to a server can have up to MAX_CONCURRENT_STREAMS requests - active and then new TCP connections are created as needed. In Go 1.10 and Go 1.11 the http2 package - would block and wait for requests to finish instead of creating new connections. - To get the stricter behavior back, import the - golang.org/x/net/http2 package - directly and set - Transport.StrictMaxConcurrentStreams to - true. -

    - -
    - -
    net/url
    -
    -

    - Parse, - ParseRequestURI, - and - URL.Parse - now return an - error for URLs containing ASCII control characters, which includes NULL, - tab, and newlines. -

    - -
    - -
    net/http/httputil
    -
    -

    - The ReverseProxy now automatically - proxies WebSocket requests. -

    - -
    - -
    os
    -
    -

    - The new ProcessState.ExitCode method - returns the process's exit code. -

    - -

    - ModeCharDevice has been added to the ModeType bitmask, allowing for - ModeDevice | ModeCharDevice to be recovered when masking a - FileMode with ModeType. -

    - -

    - The new function UserHomeDir returns the - current user's home directory. -

    - -

    - RemoveAll now supports paths longer than 4096 characters - on most Unix systems. -

    - -

    - File.Sync now uses F_FULLFSYNC on macOS - to correctly flush the file contents to permanent storage. - This may cause the method to run more slowly than in previous releases. -

    - -

    - File now supports - a SyscallConn - method returning - a syscall.RawConn - interface value. This may be used to invoke system-specific - operations on the underlying file descriptor. -

    - -
    - -
    path/filepath
    -
    -

    - The IsAbs function now returns true when passed - a reserved filename on Windows such as NUL. - List of reserved names. -

    - -
    - -
    reflect
    -
    -

    - A new MapIter type is - an iterator for ranging over a map. This type is exposed through the - Value type's new - MapRange method. - This follows the same iteration semantics as a range statement, with Next - to advance the iterator, and Key/Value to access each entry. -

    - -
    - -
    regexp
    -
    -

    - Copy is no longer necessary - to avoid lock contention, so it has been given a partial deprecation comment. - Copy - may still be appropriate if the reason for its use is to make two copies with - different Longest settings. -

    - -
    - -
    runtime/debug
    -
    -

    - A new BuildInfo type - exposes the build information read from the running binary, available only in - binaries built with module support. This includes the main package path, main - module information, and the module dependencies. This type is given through the - ReadBuildInfo function - on BuildInfo. -

    - -
    - -
    strings
    -
    -

    - The new function ReplaceAll returns a copy of - a string with all non-overlapping instances of a value replaced by another. -

    - -

    - A pointer to a zero-value Reader is now - functionally equivalent to NewReader(nil). - Prior to Go 1.12, the former could not be used as a substitute for the latter in all cases. -

    - -

    - The new Builder.Cap method returns the capacity of the builder's underlying byte slice. -

    - -

    - The character mapping functions Map, - Title, - ToLower, - ToLowerSpecial, - ToTitle, - ToTitleSpecial, - ToUpper, and - ToUpperSpecial - now always guarantee to return valid UTF-8. In earlier releases, if the input was invalid UTF-8 but no character replacements - needed to be applied, these routines incorrectly returned the invalid UTF-8 unmodified. -

    - -
    - -
    syscall
    -
    -

    - 64-bit inodes are now supported on FreeBSD 12. Some types have been adjusted accordingly. -

    - -

    - The Unix socket - (AF_UNIX) - address family is now supported for compatible versions of Windows. -

    - -

    - The new function Syscall18 - has been introduced for Windows, allowing for calls with up to 18 arguments. -

    - -
    - -
    syscall/js
    -
    -

    -

    - The Callback type and NewCallback function have been renamed; - they are now called - Func and - FuncOf, respectively. - This is a breaking change, but WebAssembly support is still experimental - and not yet subject to the - Go 1 compatibility promise. Any code using the - old names will need to be updated. -

    - -

    - If a type implements the new - Wrapper - interface, - ValueOf - will use it to return the JavaScript value for that type. -

    - -

    - The meaning of the zero - Value - has changed. It now represents the JavaScript undefined value - instead of the number zero. - This is a breaking change, but WebAssembly support is still experimental - and not yet subject to the - Go 1 compatibility promise. Any code relying on - the zero Value - to mean the number zero will need to be updated. -

    - -

    - The new - Value.Truthy - method reports the - JavaScript "truthiness" - of a given value. -

    - -
    - -
    testing
    -
    -

    - The -benchtime flag now supports setting an explicit iteration count instead of a time when the value ends with an "x". For example, -benchtime=100x runs the benchmark 100 times. -

    - -
    - -
    text/template
    -
    -

    - When executing a template, long context values are no longer truncated in errors. -

    -

    - executing "tmpl" at <.very.deep.context.v...>: map has no entry for key "notpresent" -

    -

    - is now -

    -

    - executing "tmpl" at <.very.deep.context.value.notpresent>: map has no entry for key "notpresent" -

    - -
    -

    - If a user-defined function called by a template panics, the - panic is now caught and returned as an error by - the Execute or ExecuteTemplate method. -

    -
    - -
    time
    -
    -

    - The time zone database in $GOROOT/lib/time/zoneinfo.zip - has been updated to version 2018i. Note that this ZIP file is - only used if a time zone database is not provided by the operating - system. -

    - -
    - -
    unsafe
    -
    -

    - It is invalid to convert a nil unsafe.Pointer to uintptr and back with arithmetic. - (This was already invalid, but will now cause the compiler to misbehave.) -

    - -
    diff --git a/doc/go1.13.html b/doc/go1.13.html deleted file mode 100644 index 8f4035d87f..0000000000 --- a/doc/go1.13.html +++ /dev/null @@ -1,1066 +0,0 @@ - - - - - - -

    Introduction to Go 1.13

    - -

    - The latest Go release, version 1.13, arrives six months after Go 1.12. - Most of its changes are in the implementation of the toolchain, runtime, and libraries. - As always, the release maintains the Go 1 promise of compatibility. - We expect almost all Go programs to continue to compile and run as before. -

    - -

    - As of Go 1.13, the go command by default downloads and authenticates - modules using the Go module mirror and Go checksum database run by Google. See - https://proxy.golang.org/privacy - for privacy information about these services and the - go command documentation - for configuration details including how to disable the use of these servers or use - different ones. If you depend on non-public modules, see the - documentation for configuring your environment. -

    - -

    Changes to the language

    - -

    - Per the number literal proposal, - Go 1.13 supports a more uniform and modernized set of number literal prefixes. -

      -
    • - Binary integer literals: - The prefix 0b or 0B indicates a binary integer literal - such as 0b1011. -
    • - -
    • - Octal integer literals: - The prefix 0o or 0O indicates an octal integer literal - such as 0o660. - The existing octal notation indicated by a leading 0 followed by - octal digits remains valid. -
    • - -
    • - Hexadecimal floating point literals: - The prefix 0x or 0X may now be used to express the mantissa of a - floating-point number in hexadecimal format such as 0x1.0p-1021. - A hexadecimal floating-point number must always have an exponent, written as the letter - p or P followed by an exponent in decimal. The exponent scales - the mantissa by 2 to the power of the exponent. -
    • - -
    • - Imaginary literals: - The imaginary suffix i may now be used with any (binary, decimal, hexadecimal) - integer or floating-point literal. -
    • - -
    • - Digit separators: - The digits of any number literal may now be separated (grouped) using underscores, such as - in 1_000_000, 0b_1010_0110, or 3.1415_9265. - An underscore may appear between any two digits or the literal prefix and the first digit. -
    • -
    -

    - -

    - Per the signed shift counts proposal - Go 1.13 removes the restriction that a shift count - must be unsigned. This change eliminates the need for many artificial uint conversions, - solely introduced to satisfy this (now removed) restriction of the << and >> operators. -

    - -

    - These language changes were implemented by changes to the compiler, and corresponding internal changes to the library - packages go/scanner and - text/scanner (number literals), - and go/types (signed shift counts). -

    - -

    - If your code uses modules and your go.mod files specifies a language version, be sure - it is set to at least 1.13 to get access to these language changes. - You can do this by editing the go.mod file directly, or you can run - go mod edit -go=1.13. -

    - -

    Ports

    - -

    - Go 1.13 is the last release that will run on Native Client (NaCl). -

    - -

    - For GOARCH=wasm, the new environment variable GOWASM takes a comma-separated list of experimental features that the binary gets compiled with. - The valid values are documented here. -

    - -

    AIX

    - -

    - AIX on PPC64 (aix/ppc64) now supports cgo, external - linking, and the c-archive and pie build - modes. -

    - -

    Android

    - -

    - Go programs are now compatible with Android 10. -

    - -

    Darwin

    - -

    - As announced in the Go 1.12 release notes, - Go 1.13 now requires macOS 10.11 El Capitan or later; - support for previous versions has been discontinued. -

    - -

    FreeBSD

    - -

    - As announced in the Go 1.12 release notes, - Go 1.13 now requires FreeBSD 11.2 or later; - support for previous versions has been discontinued. - FreeBSD 12.0 or later requires a kernel with the COMPAT_FREEBSD11 - option set (this is the default). -

    - -

    Illumos

    - -

    - Go now supports Illumos with GOOS=illumos. - The illumos build tag implies the solaris - build tag. -

    - -

    Windows

    - -

    - The Windows version specified by internally-linked Windows binaries - is now Windows 7 rather than NT 4.0. This was already the minimum - required version for Go, but can affect the behavior of system calls - that have a backwards-compatibility mode. These will now behave as - documented. Externally-linked binaries (any program using cgo) have - always specified a more recent Windows version. -

    - -

    Tools

    - -

    Modules

    - -

    Environment variables

    - -

    - The GO111MODULE - environment variable continues to default to auto, but - the auto setting now activates the module-aware mode of - the go command whenever the current working directory contains, - or is below a directory containing, a go.mod file — even if the - current directory is within GOPATH/src. This change simplifies - the migration of existing code within GOPATH/src and the ongoing - maintenance of module-aware packages alongside non-module-aware importers. -

    - -

    - The new - GOPRIVATE - environment variable indicates module paths that are not publicly available. - It serves as the default value for the lower-level GONOPROXY - and GONOSUMDB variables, which provide finer-grained control over - which modules are fetched via proxy and verified using the checksum database. -

    - -

    - The GOPROXY - environment variable may now be set to a comma-separated list of proxy - URLs or the special token direct, and - its default value is - now https://proxy.golang.org,direct. When resolving a package - path to its containing module, the go command will try all - candidate module paths on each proxy in the list in succession. An unreachable - proxy or HTTP status code other than 404 or 410 terminates the search without - consulting the remaining proxies. -

    - -

    - The new - GOSUMDB - environment variable identifies the name, and optionally the public key and - server URL, of the database to consult for checksums of modules that are not - yet listed in the main module's go.sum file. - If GOSUMDB does not include an explicit URL, the URL is chosen by - probing the GOPROXY URLs for an endpoint indicating support for - the checksum database, falling back to a direct connection to the named - database if it is not supported by any proxy. If GOSUMDB is set - to off, the checksum database is not consulted and only the - existing checksums in the go.sum file are verified. -

    - -

    - Users who cannot reach the default proxy and checksum database (for example, - due to a firewalled or sandboxed configuration) may disable their use by - setting GOPROXY to direct, and/or - GOSUMDB to off. - go env -w - can be used to set the default values for these variables independent of - platform: -

    -
    -go env -w GOPROXY=direct
    -go env -w GOSUMDB=off
    -
    - -

    go get

    - -

    - In module-aware mode, - go get - with the -u flag now updates a smaller set of modules that is - more consistent with the set of packages updated by - go get -u in GOPATH mode. - go get -u continues to update the - modules and packages named on the command line, but additionally updates only - the modules containing the packages imported by the named packages, - rather than the transitive module requirements of the modules containing the - named packages. -

    - -

    - Note in particular that go get -u - (without additional arguments) now updates only the transitive imports of the - package in the current directory. To instead update all of the packages - transitively imported by the main module (including test dependencies), use - go get -u all. -

    - -

    - As a result of the above changes to - go get -u, the - go get subcommand no longer supports - the -m flag, which caused go get to - stop before loading packages. The -d flag remains supported, and - continues to cause go get to stop after downloading - the source code needed to build dependencies of the named packages. -

    - -

    - By default, go get -u in module mode - upgrades only non-test dependencies, as in GOPATH mode. It now also accepts - the -t flag, which (as in GOPATH mode) - causes go get to include the packages imported - by tests of the packages named on the command line. -

    - -

    - In module-aware mode, the go get subcommand now - supports the version suffix @patch. The @patch - suffix indicates that the named module, or module containing the named - package, should be updated to the highest patch release with the same - major and minor versions as the version found in the build list. -

    - -

    - If a module passed as an argument to go get - without a version suffix is already required at a newer version than the - latest released version, it will remain at the newer version. This is - consistent with the behavior of the -u flag for module - dependencies. This prevents unexpected downgrades from pre-release versions. - The new version suffix @upgrade explicitly requests this - behavior. @latest explicitly requests the latest version - regardless of the current version. -

    - -

    Version validation

    - -

    - When extracting a module from a version control system, the go - command now performs additional validation on the requested version string. -

    - -

    - The +incompatible version annotation bypasses the requirement - of semantic - import versioning for repositories that predate the introduction of - modules. The go command now verifies that such a version does not - include an explicit go.mod file. -

    - -

    - The go command now verifies the mapping - between pseudo-versions and - version-control metadata. Specifically: -

      -
    • The version prefix must be of the form vX.0.0, or derived - from a tag on an ancestor of the named revision, or derived from a tag that - includes build metadata on - the named revision itself.
    • - -
    • The date string must match the UTC timestamp of the revision.
    • - -
    • The short name of the revision must use the same number of characters as - what the go command would generate. (For SHA-1 hashes as used - by git, a 12-digit prefix.)
    • -
    -

    - -

    - If a require directive in the - main module uses - an invalid pseudo-version, it can usually be corrected by redacting the - version to just the commit hash and re-running a go command, such - as go list -m all - or go mod tidy. For example, -

    -
    require github.com/docker/docker v1.14.0-0.20190319215453-e7b5f7dbe98c
    -

    can be redacted to

    -
    require github.com/docker/docker e7b5f7dbe98c
    -

    which currently resolves to

    -
    require github.com/docker/docker v0.7.3-0.20190319215453-e7b5f7dbe98c
    - -

    - If one of the transitive dependencies of the main module requires an invalid - version or pseudo-version, the invalid version can be replaced with a valid - one using a - replace directive in - the go.mod file of the main module. If the replacement is a - commit hash, it will be resolved to the appropriate pseudo-version as above. - For example, -

    -
    replace github.com/docker/docker v1.14.0-0.20190319215453-e7b5f7dbe98c => github.com/docker/docker e7b5f7dbe98c
    -

    currently resolves to

    -
    replace github.com/docker/docker v1.14.0-0.20190319215453-e7b5f7dbe98c => github.com/docker/docker v0.7.3-0.20190319215453-e7b5f7dbe98c
    - -

    Go command

    - -

    - The go env - command now accepts a -w flag to set the per-user default value - of an environment variable recognized by the - go command, and a corresponding -u flag to unset a - previously-set default. Defaults set via - go env -w are stored in the - go/env file within - os.UserConfigDir(). -

    - -

    - The - go version command now accepts arguments naming - executables and directories. When invoked on an executable, - go version prints the version of Go used to build - the executable. If the -m flag is used, - go version prints the executable's embedded module - version information, if available. When invoked on a directory, - go version prints information about executables - contained in the directory and its subdirectories. -

    - -

    - The new go - build flag -trimpath removes all file system paths - from the compiled executable, to improve build reproducibility. -

    - -

    - If the -o flag passed to go build - refers to an existing directory, go build will now - write executable files within that directory for main packages - matching its package arguments. -

    - -

    - The go build flag -tags now takes a - comma-separated list of build tags, to allow for multiple tags in - GOFLAGS. The - space-separated form is deprecated but still recognized and will be maintained. -

    - -

    - go - generate now sets the generate build tag so that - files may be searched for directives but ignored during build. -

    - -

    - As announced in the Go 1.12 release - notes, binary-only packages are no longer supported. Building a binary-only - package (marked with a //go:binary-only-package comment) now - results in an error. -

    - -

    Compiler toolchain

    - -

    - The compiler has a new implementation of escape analysis that is - more precise. For most Go code should be an improvement (in other - words, more Go variables and expressions allocated on the stack - instead of heap). However, this increased precision may also break - invalid code that happened to work before (for example, code that - violates - the unsafe.Pointer - safety rules). If you notice any regressions that appear - related, the old escape analysis pass can be re-enabled - with go build -gcflags=all=-newescape=false. - The option to use the old escape analysis will be removed in a - future release. -

    - -

    - The compiler no longer emits floating point or complex constants - to go_asm.h files. These have always been emitted in a - form that could not be used as numeric constant in assembly code. -

    - -

    Assembler

    - -

    - The assembler now supports many of the atomic instructions - introduced in ARM v8.1. -

    - -

    gofmt

    - -

    - gofmt (and with that go fmt) now canonicalizes - number literal prefixes and exponents to use lower-case letters, but - leaves hexadecimal digits alone. This improves readability when using the new octal prefix - (0O becomes 0o), and the rewrite is applied consistently. - gofmt now also removes unnecessary leading zeroes from a decimal integer - imaginary literal. (For backwards-compatibility, an integer imaginary literal - starting with 0 is considered a decimal, not an octal number. - Removing superfluous leading zeroes avoids potential confusion.) - For instance, 0B1010, 0XabcDEF, 0O660, - 1.2E3, and 01i become 0b1010, 0xabcDEF, - 0o660, 1.2e3, and 1i after applying gofmt. -

    - -

    godoc and go doc

    - -

    - The godoc webserver is no longer included in the main binary distribution. - To run the godoc webserver locally, manually install it first: -

    -go get golang.org/x/tools/cmd/godoc
    -godoc
    -
    -

    - -

    - The - go doc - command now always includes the package clause in its output, except for - commands. This replaces the previous behavior where a heuristic was used, - causing the package clause to be omitted under certain conditions. -

    - -

    Runtime

    - -

    - Out of range panic messages now include the index that was out of - bounds and the length (or capacity) of the slice. For - example, s[3] on a slice of length 1 will panic with - "runtime error: index out of range [3] with length 1". -

    - -

    - This release improves performance of most uses of defer - by 30%. -

    - -

    - The runtime is now more aggressive at returning memory to the - operating system to make it available to co-tenant applications. - Previously, the runtime could retain memory for five or more minutes - following a spike in the heap size. It will now begin returning it - promptly after the heap shrinks. However, on many OSes, including - Linux, the OS itself reclaims memory lazily, so process RSS will not - decrease until the system is under memory pressure. -

    - -

    Core library

    - -

    TLS 1.3

    - -

    - As announced in Go 1.12, Go 1.13 enables support for TLS 1.3 in the - crypto/tls package by default. It can be disabled by adding the - value tls13=0 to the GODEBUG - environment variable. The opt-out will be removed in Go 1.14. -

    - -

    - See the Go 1.12 release notes for important - compatibility information. -

    - -

    crypto/ed25519

    - -

    - The new crypto/ed25519 - package implements the Ed25519 signature - scheme. This functionality was previously provided by the - golang.org/x/crypto/ed25519 - package, which becomes a wrapper for - crypto/ed25519 when used with Go 1.13+. -

    - -

    Error wrapping

    - -

    - Go 1.13 contains support for error wrapping, as first proposed in - the - Error Values proposal and discussed on the - associated issue. -

    -

    - An error e can wrap another error w by providing - an Unwrap method that returns w. Both e - and w are available to programs, allowing e to provide - additional context to w or to reinterpret it while still allowing - programs to make decisions based on w. -

    -

    - To support wrapping, fmt.Errorf now has a %w - verb for creating wrapped errors, and three new functions in - the errors package ( - errors.Unwrap, - errors.Is and - errors.As) simplify unwrapping - and inspecting wrapped errors. -

    -

    - For more information, read the errors package - documentation, or see - the Error Value FAQ. - There will soon be a blog post as well. -

    - -

    Minor changes to the library

    - -

    - As always, there are various minor changes and updates to the library, - made with the Go 1 promise of compatibility - in mind. -

    - -
    bytes
    -
    -

    - The new ToValidUTF8 function returns a - copy of a given byte slice with each run of invalid UTF-8 byte sequences replaced by a given slice. -

    - -
    - -
    context
    -
    -

    - The formatting of contexts returned by WithValue no longer depends on fmt and will not stringify in the same way. Code that depends on the exact previous stringification might be affected. -

    - -
    - -
    crypto/tls
    -
    -

    - Support for SSL version 3.0 (SSLv3) - is now deprecated and will be removed in Go 1.14. Note that SSLv3 is the - cryptographically broken - protocol predating TLS. -

    - -

    - SSLv3 was always disabled by default, other than in Go 1.12, when it was - mistakenly enabled by default server-side. It is now again disabled by - default. (SSLv3 was never supported client-side.) -

    - -

    - Ed25519 certificates are now supported in TLS versions 1.2 and 1.3. -

    - -
    - -
    crypto/x509
    -
    -

    - Ed25519 keys are now supported in certificates and certificate requests - according to RFC 8410, as well as by the - ParsePKCS8PrivateKey, - MarshalPKCS8PrivateKey, - and ParsePKIXPublicKey functions. -

    - -

    - The paths searched for system roots now include /etc/ssl/cert.pem - to support the default location in Alpine Linux 3.7+. -

    - -
    - -
    database/sql
    -
    -

    - The new NullTime type represents a time.Time that may be null. -

    - -

    - The new NullInt32 type represents an int32 that may be null. -

    - -
    - -
    debug/dwarf
    -
    -

    - The Data.Type - method no longer panics if it encounters an unknown DWARF tag in - the type graph. Instead, it represents that component of the - type with - an UnsupportedType - object. -

    - -
    - -
    errors
    -
    - -

    - The new function As finds the first - error in a given error’s chain (sequence of wrapped errors) - that matches a given target’s type, and if so, sets the target to that error value. -

    -

    - The new function Is reports whether a given error value matches an - error in another’s chain. -

    -

    - The new function Unwrap returns the result of calling - Unwrap on a given error, if one exists. -

    - -
    - -
    fmt
    -
    - -

    - The printing verbs %x and %X now format floating-point and - complex numbers in hexadecimal notation, in lower-case and upper-case respectively. -

    - - -

    - The new printing verb %O formats integers in base 8, emitting the 0o prefix. -

    - - -

    - The scanner now accepts hexadecimal floating-point values, digit-separating underscores - and leading 0b and 0o prefixes. - See the Changes to the language for details. -

    - - -

    The Errorf function - has a new verb, %w, whose operand must be an error. - The error returned from Errorf will have an - Unwrap method which returns the operand of %w. -

    - -
    - - -
    go/scanner
    -
    -

    - The scanner has been updated to recognize the new Go number literals, specifically - binary literals with 0b/0B prefix, octal literals with 0o/0O prefix, - and floating-point numbers with hexadecimal mantissa. The imaginary suffix i may now be used with any number - literal, and underscores may used as digit separators for grouping. - See the Changes to the language for details. -

    - -
    - -
    go/types
    -
    -

    - The type-checker has been updated to follow the new rules for integer shifts. - See the Changes to the language for details. -

    - -
    - - - -
    html/template
    -
    -

    - When using a <script> tag with "module" set as the - type attribute, code will now be interpreted as JavaScript module script. -

    - -
    - -
    log
    -
    -

    - The new Writer function returns the output destination for the standard logger. -

    - -
    - -
    math/big
    -
    -

    - The new Rat.SetUint64 method sets the Rat to a uint64 value. -

    - -

    - For Float.Parse, if base is 0, underscores - may be used between digits for readability. - See the Changes to the language for details. -

    - -

    - For Int.SetString, if base is 0, underscores - may be used between digits for readability. - See the Changes to the language for details. -

    - -

    - Rat.SetString now accepts non-decimal floating point representations. -

    - -
    - -
    math/bits
    -
    -

    - The execution time of Add, - Sub, - Mul, - RotateLeft, and - ReverseBytes is now - guaranteed to be independent of the inputs. -

    - -
    - -
    net
    -
    -

    - On Unix systems where use-vc is set in resolv.conf, TCP is used for DNS resolution. -

    - -

    - The new field ListenConfig.KeepAlive - specifies the keep-alive period for network connections accepted by the listener. - If this field is 0 (the default) TCP keep-alives will be enabled. - To disable them, set it to a negative value. -

    -

    - Note that the error returned from I/O on a connection that was - closed by a keep-alive timeout will have a - Timeout method that returns true if called. - This can make a keep-alive error difficult to distinguish from - an error returned due to a missed deadline as set by the - SetDeadline - method and similar methods. - Code that uses deadlines and checks for them with - the Timeout method or - with os.IsTimeout - may want to disable keep-alives, or - use errors.Is(syscall.ETIMEDOUT) (on Unix systems) - which will return true for a keep-alive timeout and false for a - deadline timeout. -

    - -
    - -
    net/http
    -
    -

    - The new fields Transport.WriteBufferSize - and Transport.ReadBufferSize - allow one to specify the sizes of the write and read buffers for a Transport. - If either field is zero, a default size of 4KB is used. -

    - -

    - The new field Transport.ForceAttemptHTTP2 - controls whether HTTP/2 is enabled when a non-zero Dial, DialTLS, or DialContext - func or TLSClientConfig is provided. -

    - -

    - Transport.MaxConnsPerHost now works - properly with HTTP/2. -

    - -

    - TimeoutHandler's - ResponseWriter now implements the - Pusher interface. -

    - -

    - The StatusCode 103 "Early Hints" has been added. -

    - -

    - Transport now uses the Request.Body's - io.ReaderFrom implementation if available, to optimize writing the body. -

    - -

    - On encountering unsupported transfer-encodings, http.Server now - returns a "501 Unimplemented" status as mandated by the HTTP specification RFC 7230 Section 3.3.1. -

    - -

    - The new Server fields - BaseContext and - ConnContext - allow finer control over the Context values provided to requests and connections. -

    - -

    - http.DetectContentType now correctly detects RAR signatures, and can now also detect RAR v5 signatures. -

    - -

    - The new Header method - Clone returns a copy of the receiver. -

    - -

    - A new function NewRequestWithContext has been added and it - accepts a Context that controls the entire lifetime of - the created outgoing Request, suitable for use with - Client.Do and Transport.RoundTrip. -

    - -

    - The Transport no longer logs errors when servers - gracefully shut down idle connections using a "408 Request Timeout" response. -

    - -
    - -
    os
    -
    -

    - The new UserConfigDir function - returns the default directory to use for user-specific configuration data. -

    - -

    - If a File is opened using the O_APPEND flag, its - WriteAt method will always return an error. -

    - -
    - -
    os/exec
    -
    -

    - On Windows, the environment for a Cmd always inherits the - %SYSTEMROOT% value of the parent process unless the - Cmd.Env field includes an explicit value for it. -

    - -
    - -
    reflect
    -
    -

    - The new Value.IsZero method reports whether a Value is the zero value for its type. -

    - -

    - The MakeFunc function now allows assignment conversions on returned values, instead of requiring exact type match. This is particularly useful when the type being returned is an interface type, but the value actually returned is a concrete value implementing that type. -

    - -
    - -
    runtime
    -
    -

    - Tracebacks, runtime.Caller, - and runtime.Callers now refer to the function that - initializes the global variables of PKG - as PKG.init instead of PKG.init.ializers. -

    - -
    - -
    strconv
    -
    -

    - For strconv.ParseFloat, - strconv.ParseInt - and strconv.ParseUint, - if base is 0, underscores may be used between digits for readability. - See the Changes to the language for details. -

    - -
    - -
    strings
    -
    -

    - The new ToValidUTF8 function returns a - copy of a given string with each run of invalid UTF-8 byte sequences replaced by a given string. -

    - -
    - -
    sync
    -
    -

    - The fast paths of Mutex.Lock, Mutex.Unlock, - RWMutex.Lock, RWMutex.RUnlock, and - Once.Do are now inlined in their callers. - For the uncontended cases on amd64, these changes make Once.Do twice as fast, and the - Mutex/RWMutex methods up to 10% faster. -

    - -

    - Large Pool no longer increase stop-the-world pause times. -

    - -

    - Pool no longer needs to be completely repopulated after every GC. It now retains some objects across GCs, - as opposed to releasing all objects, reducing load spikes for heavy users of Pool. -

    - -
    - -
    syscall
    -
    -

    - Uses of _getdirentries64 have been removed from - Darwin builds, to allow Go binaries to be uploaded to the macOS - App Store. -

    - -

    - The new ProcessAttributes and ThreadAttributes fields in - SysProcAttr have been introduced for Windows, - exposing security settings when creating new processes. -

    - -

    - EINVAL is no longer returned in zero - Chmod mode on Windows. -

    - -

    - Values of type Errno can be tested against error values in - the os package, - like ErrExist, using - errors.Is. -

    - -
    - -
    syscall/js
    -
    -

    - TypedArrayOf has been replaced by - CopyBytesToGo and - CopyBytesToJS for copying bytes - between a byte slice and a Uint8Array. -

    - -
    - -
    testing
    -
    -

    - When running benchmarks, B.N is no longer rounded. -

    - -

    - The new method B.ReportMetric lets users report - custom benchmark metrics and override built-in metrics. -

    - -

    - Testing flags are now registered in the new Init function, - which is invoked by the generated main function for the test. - As a result, testing flags are now only registered when running a test binary, - and packages that call flag.Parse during package initialization may cause tests to fail. -

    - -
    - -
    text/scanner
    -
    -

    - The scanner has been updated to recognize the new Go number literals, specifically - binary literals with 0b/0B prefix, octal literals with 0o/0O prefix, - and floating-point numbers with hexadecimal mantissa. - Also, the new AllowDigitSeparators - mode allows number literals to contain underscores as digit separators (off by default for backwards-compatibility). - See the Changes to the language for details. -

    - -
    - -
    text/template
    -
    -

    - The new slice function - returns the result of slicing its first argument by the following arguments. -

    - -
    - -
    time
    -
    -

    - Day-of-year is now supported by Format - and Parse. -

    - -

    - The new Duration methods - Microseconds and - Milliseconds return - the duration as an integer count of their respectively named units. -

    - -
    - -
    unicode
    -
    -

    - The unicode package and associated - support throughout the system has been upgraded from Unicode 10.0 to - Unicode 11.0, - which adds 684 new characters, including seven new scripts, and 66 new emoji. -

    - -
    diff --git a/doc/go1.14.html b/doc/go1.14.html deleted file mode 100644 index 410e0cbf7c..0000000000 --- a/doc/go1.14.html +++ /dev/null @@ -1,924 +0,0 @@ - - - - - - -

    Introduction to Go 1.14

    - -

    - The latest Go release, version 1.14, arrives six months after Go 1.13. - Most of its changes are in the implementation of the toolchain, runtime, and libraries. - As always, the release maintains the Go 1 promise of compatibility. - We expect almost all Go programs to continue to compile and run as before. -

    - -

    - Module support in the go command is now ready for production use, - and we encourage all users to migrate to Go - modules for dependency management. If you are unable to migrate due to a problem in the Go - toolchain, please ensure that the problem has an - open issue - filed. (If the issue is not on the Go1.15 milestone, please let us - know why it prevents you from migrating so that we can prioritize it - appropriately.) -

    - -

    Changes to the language

    - -

    - Per the overlapping interfaces proposal, - Go 1.14 now permits embedding of interfaces with overlapping method sets: - methods from an embedded interface may have the same names and identical signatures - as methods already present in the (embedding) interface. This solves problems that typically - (but not exclusively) occur with diamond-shaped embedding graphs. - Explicitly declared methods in an interface must remain - unique, as before. -

    - -

    Ports

    - -

    Darwin

    - -

    - Go 1.14 is the last release that will run on macOS 10.11 El Capitan. - Go 1.15 will require macOS 10.12 Sierra or later. -

    - -

    - Go 1.14 is the last Go release to support 32-bit binaries on - macOS (the darwin/386 port). They are no longer - supported by macOS, starting with macOS 10.15 (Catalina). - Go continues to support the 64-bit darwin/amd64 port. -

    - -

    - Go 1.14 will likely be the last Go release to support 32-bit - binaries on iOS, iPadOS, watchOS, and tvOS - (the darwin/arm port). Go continues to support the - 64-bit darwin/arm64 port. -

    - -

    Windows

    - -

    - Go binaries on Windows now - have DEP - (Data Execution Prevention) enabled. -

    - -

    - On Windows, creating a file - via os.OpenFile with - the os.O_CREATE flag, or - via syscall.Open with - the syscall.O_CREAT - flag, will now create the file as read-only if the - bit 0o200 (owner write permission) is not set in the - permission argument. This makes the behavior on Windows more like - that on Unix systems. -

    - -

    WebAssembly

    - -

    - JavaScript values referenced from Go via js.Value - objects can now be garbage collected. -

    - -

    - js.Value values can no longer be compared using - the == operator, and instead must be compared using - their Equal method. -

    - -

    - js.Value now - has IsUndefined, IsNull, - and IsNaN methods. -

    - -

    RISC-V

    - -

    - Go 1.14 contains experimental support for 64-bit RISC-V on Linux - (GOOS=linux, GOARCH=riscv64). Be aware - that performance, assembly syntax stability, and possibly - correctness are a work in progress. -

    - -

    FreeBSD

    - -

    - Go now supports the 64-bit ARM architecture on FreeBSD 12.0 or later (the - freebsd/arm64 port). -

    - -

    Native Client (NaCl)

    - -

    - As announced in the Go 1.13 release notes, - Go 1.14 drops support for the Native Client platform (GOOS=nacl). -

    - -

    Illumos

    - -

    - The runtime now respects zone CPU caps - (the zone.cpu-cap resource control) - for runtime.NumCPU and the default value - of GOMAXPROCS. -

    - -

    Tools

    - -

    Go command

    - -

    Vendoring

    - - -

    - When the main module contains a top-level vendor directory and - its go.mod file specifies go 1.14 or - higher, the go command now defaults to -mod=vendor - for operations that accept that flag. A new value for that flag, - -mod=mod, causes the go command to instead load - modules from the module cache (as when no vendor directory is - present). -

    - -

    - When -mod=vendor is set (explicitly or by default), the - go command now verifies that the main module's - vendor/modules.txt file is consistent with its - go.mod file. -

    - -

    - go list -m no longer silently omits - transitive dependencies that do not provide packages in - the vendor directory. It now fails explicitly if - -mod=vendor is set and information is requested for a module not - mentioned in vendor/modules.txt. -

    - -

    Flags

    - -

    - The go get command no longer accepts - the -mod flag. Previously, the flag's setting either - was ignored or - caused the build to fail. -

    - -

    - -mod=readonly is now set by default when the go.mod - file is read-only and no top-level vendor directory is present. -

    - -

    - -modcacherw is a new flag that instructs the go - command to leave newly-created directories in the module cache at their - default permissions rather than making them read-only. - The use of this flag makes it more likely that tests or other tools will - accidentally add files not included in the module's verified checksum. - However, it allows the use of rm -rf - (instead of go clean -modcache) - to remove the module cache. -

    - -

    - -modfile=file is a new flag that instructs the go - command to read (and possibly write) an alternate go.mod file - instead of the one in the module root directory. A file - named go.mod must still be present in order to determine the - module root directory, but it is not accessed. When -modfile is - specified, an alternate go.sum file is also used: its path is - derived from the -modfile flag by trimming the .mod - extension and appending .sum. -

    - -

    Environment variables

    - -

    - GOINSECURE is a new environment variable that instructs - the go command to not require an HTTPS connection, and to skip - certificate validation, when fetching certain modules directly from their - origins. Like the existing GOPRIVATE variable, the value - of GOINSECURE is a comma-separated list of glob patterns. -

    - -

    Commands outside modules

    - -

    - When module-aware mode is enabled explicitly (by setting - GO111MODULE=on), most module commands have more - limited functionality if no go.mod file is present. For - example, go build, - go run, and other build commands can only build - packages in the standard library and packages specified as .go - files on the command line. -

    - -

    - Previously, the go command would resolve each package path - to the latest version of a module but would not record the module path - or version. This resulted in slow, - non-reproducible builds. -

    - -

    - go get continues to work as before, as do - go mod download and - go list -m with explicit versions. -

    - -

    +incompatible versions

    - - -

    - If the latest version of a module contains a go.mod file, - go get will no longer upgrade to an - incompatible - major version of that module unless such a version is requested explicitly - or is already required. - go list also omits incompatible major versions - for such a module when fetching directly from version control, but may - include them if reported by a proxy. -

    - - -

    go.mod file maintenance

    - - -

    - go commands other than - go mod tidy no longer - remove a require directive that specifies a version of an indirect dependency - that is already implied by other (transitive) dependencies of the main - module. -

    - -

    - go commands other than - go mod tidy no longer - edit the go.mod file if the changes are only cosmetic. -

    - -

    - When -mod=readonly is set, go commands will no - longer fail due to a missing go directive or an erroneous - // indirect comment. -

    - -

    Module downloading

    - -

    - The go command now supports Subversion repositories in module mode. -

    - -

    - The go command now includes snippets of plain-text error messages - from module proxies and other HTTP servers. - An error message will only be shown if it is valid UTF-8 and consists of only - graphic characters and spaces. -

    - -

    Testing

    - -

    - go test -v now streams t.Log output as it happens, - rather than at the end of all tests. -

    - -

    Runtime

    - -

    - This release improves the performance of most uses - of defer to incur almost zero overhead compared to - calling the deferred function directly. - As a result, defer can now be used in - performance-critical code without overhead concerns. -

    - -

    - Goroutines are now asynchronously preemptible. - As a result, loops without function calls no longer potentially - deadlock the scheduler or significantly delay garbage collection. - This is supported on all platforms except windows/arm, - darwin/arm, js/wasm, and - plan9/*. -

    - -

    - A consequence of the implementation of preemption is that on Unix - systems, including Linux and macOS systems, programs built with Go - 1.14 will receive more signals than programs built with earlier - releases. - This means that programs that use packages - like syscall - or golang.org/x/sys/unix - will see more slow system calls fail with EINTR errors. - Those programs will have to handle those errors in some way, most - likely looping to try the system call again. For more - information about this - see man - 7 signal for Linux systems or similar documentation for - other systems. -

    - -

    - The page allocator is more efficient and incurs significantly less - lock contention at high values of GOMAXPROCS. - This is most noticeable as lower latency and higher throughput for - large allocations being done in parallel and at a high rate. -

    - -

    - Internal timers, used by - time.After, - time.Tick, - net.Conn.SetDeadline, - and friends, are more efficient, with less lock contention and fewer - context switches. - This is a performance improvement that should not cause any user - visible changes. -

    - -

    Compiler

    - -

    - This release adds -d=checkptr as a compile-time option - for adding instrumentation to check that Go code is following - unsafe.Pointer safety rules dynamically. - This option is enabled by default (except on Windows) with - the -race or -msan flags, and can be - disabled with -gcflags=all=-d=checkptr=0. - Specifically, -d=checkptr checks the following: -

    - -
      -
    1. - When converting unsafe.Pointer to *T, - the resulting pointer must be aligned appropriately - for T. -
    2. -
    3. - If the result of pointer arithmetic points into a Go heap object, - one of the unsafe.Pointer-typed operands must point - into the same object. -
    4. -
    - -

    - Using -d=checkptr is not currently recommended on - Windows because it causes false alerts in the standard library. -

    - -

    - The compiler can now emit machine-readable logs of key optimizations - using the -json flag, including inlining, escape - analysis, bounds-check elimination, and nil-check elimination. -

    - -

    - Detailed escape analysis diagnostics (-m=2) now work again. - This had been dropped from the new escape analysis implementation in - the previous release. -

    - -

    - All Go symbols in macOS binaries now begin with an underscore, - following platform conventions. -

    - -

    - This release includes experimental support for compiler-inserted - coverage instrumentation for fuzzing. - See issue 14565 for more - details. - This API may change in future releases. -

    - -

    - Bounds check elimination now uses information from slice creation and can - eliminate checks for indexes with types smaller than int. -

    - -

    Core library

    - -

    New byte sequence hashing package

    - -

    - Go 1.14 includes a new package, - hash/maphash, - which provides hash functions on byte sequences. - These hash functions are intended to be used to implement hash tables or - other data structures that need to map arbitrary strings or byte - sequences to a uniform distribution on unsigned 64-bit integers. -

    -

    - The hash functions are collision-resistant but not cryptographically secure. -

    -

    - The hash value of a given byte sequence is consistent within a - single process, but will be different in different processes. -

    - -

    Minor changes to the library

    - -

    - As always, there are various minor changes and updates to the library, - made with the Go 1 promise of compatibility - in mind. -

    - -
    crypto/tls
    -
    -

    - Support for SSL version 3.0 (SSLv3) has been removed. Note that SSLv3 is the - cryptographically broken - protocol predating TLS. -

    - -

    - TLS 1.3 can't be disabled via the GODEBUG environment - variable anymore. Use the - Config.MaxVersion - field to configure TLS versions. -

    - -

    - When multiple certificate chains are provided through the - Config.Certificates - field, the first one compatible with the peer is now automatically - selected. This allows for example providing an ECDSA and an RSA - certificate, and letting the package automatically select the best one. - Note that the performance of this selection is going to be poor unless the - Certificate.Leaf - field is set. The - Config.NameToCertificate - field, which only supports associating a single certificate with - a give name, is now deprecated and should be left as nil. - Similarly the - Config.BuildNameToCertificate - method, which builds the NameToCertificate field - from the leaf certificates, is now deprecated and should not be - called. -

    - -

    - The new CipherSuites - and InsecureCipherSuites - functions return a list of currently implemented cipher suites. - The new CipherSuiteName - function returns a name for a cipher suite ID. -

    - -

    - The new - (*ClientHelloInfo).SupportsCertificate and - - (*CertificateRequestInfo).SupportsCertificate - methods expose whether a peer supports a certain certificate. -

    - -

    - The tls package no longer supports the legacy Next Protocol - Negotiation (NPN) extension and now only supports ALPN. In previous - releases it supported both. There are no API changes and applications - should function identically as before. Most other clients and servers have - already removed NPN support in favor of the standardized ALPN. -

    - -

    - RSA-PSS signatures are now used when supported in TLS 1.2 handshakes. This - won't affect most applications, but custom - Certificate.PrivateKey - implementations that don't support RSA-PSS signatures will need to use the new - - Certificate.SupportedSignatureAlgorithms - field to disable them. -

    - -

    - Config.Certificates and - Config.GetCertificate - can now both be nil if - Config.GetConfigForClient - is set. If the callbacks return neither certificates nor an error, the - unrecognized_name is now sent. -

    - -

    - The new CertificateRequestInfo.Version - field provides the TLS version to client certificates callbacks. -

    - -

    - The new TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 and - TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 constants use - the final names for the cipher suites previously referred to as - TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305 and - TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305. -

    -
    -
    - -
    crypto/x509
    -
    -

    - Certificate.CreateCRL - now supports Ed25519 issuers. -

    -
    -
    - -
    debug/dwarf
    -
    -

    - The debug/dwarf package now supports reading DWARF - version 5. -

    -

    - The new - method (*Data).AddSection - supports adding arbitrary new DWARF sections from the input file - to the DWARF Data. -

    - -

    - The new - method (*Reader).ByteOrder - returns the byte order of the current compilation unit. - This may be used to interpret attributes that are encoded in the - native ordering, such as location descriptions. -

    - -

    - The new - method (*LineReader).Files - returns the file name table from a line reader. - This may be used to interpret the value of DWARF attributes such - as AttrDeclFile. -

    -
    -
    - -
    encoding/asn1
    -
    -

    - Unmarshal - now supports ASN.1 string type BMPString, represented by the new - TagBMPString - constant. -

    -
    -
    - -
    encoding/json
    -
    -

    - The Decoder - type supports a new - method InputOffset - that returns the input stream byte offset of the current - decoder position. -

    - -

    - Compact no longer - escapes the U+2028 and U+2029 characters, which - was never a documented feature. For proper escaping, see HTMLEscape. -

    - -

    - Number no longer - accepts invalid numbers, to follow the documented behavior more closely. - If a program needs to accept invalid numbers like the empty string, - consider wrapping the type with Unmarshaler. -

    - -

    - Unmarshal - can now support map keys with string underlying type which implement - encoding.TextUnmarshaler. -

    -
    -
    - -
    go/build
    -
    -

    - The Context - type has a new field Dir which may be used to set - the working directory for the build. - The default is the current directory of the running process. - In module mode, this is used to locate the main module. -

    -
    -
    - -
    go/doc
    -
    -

    - The new - function NewFromFiles - computes package documentation from a list - of *ast.File's and associates examples with the - appropriate package elements. - The new information is available in a new Examples - field - in the Package, Type, - and Func types, and a - new Suffix - field in - the Example - type. -

    -
    -
    - -
    io/ioutil
    -
    -

    - TempDir can now create directories - whose names have predictable prefixes and suffixes. - As with TempFile, if the pattern - contains a '*', the random string replaces the last '*'. -

    -
    -
    - -
    log
    -
    -

    - The - new Lmsgprefix - flag may be used to tell the logging functions to emit the - optional output prefix immediately before the log message rather - than at the start of the line. -

    -
    -
    - -
    math
    -
    -

    - The new FMA function - computes x*y+z in floating point with no - intermediate rounding of the x*y - computation. Several architectures implement this computation - using dedicated hardware instructions for additional performance. -

    -
    -
    - -
    math/big
    -
    -

    - The GCD method - now allows the inputs a and b to be - zero or negative. -

    -
    -
    - -
    math/bits
    -
    -

    - The new functions - Rem, - Rem32, and - Rem64 - support computing a remainder even when the quotient overflows. -

    -
    -
    - -
    mime
    -
    -

    - The default type of .js and .mjs files - is now text/javascript rather - than application/javascript. - This is in accordance - with an - IETF draft that treats application/javascript as obsolete. -

    -
    -
    - -
    mime/multipart
    -
    -

    - The - new Reader - method NextRawPart - supports fetching the next MIME part without transparently - decoding quoted-printable data. -

    -
    -
    - -
    net/http
    -
    -

    - The new Header - method Values - can be used to fetch all values associated with a - canonicalized key. -

    - -

    - The - new Transport - field DialTLSContext - can be used to specify an optional dial function for creating - TLS connections for non-proxied HTTPS requests. - This new field can be used instead - of DialTLS, - which is now considered deprecated; DialTLS will - continue to work, but new code should - use DialTLSContext, which allows the transport to - cancel dials as soon as they are no longer needed. -

    - -

    - On Windows, ServeFile now correctly - serves files larger than 2GB. -

    -
    -
    - -
    net/http/httptest
    -
    -

    - The - new Server - field EnableHTTP2 - supports enabling HTTP/2 on the test server. -

    -
    -
    - -
    net/textproto
    -
    -

    - The - new MIMEHeader - method Values - can be used to fetch all values associated with a canonicalized - key. -

    -
    -
    - -
    net/url
    -
    -

    - When parsing of a URL fails - (for example by Parse - or ParseRequestURI), - the resulting Error message - will now quote the unparsable URL. - This provides clearer structure and consistency with other parsing errors. -

    -
    -
    - -
    os/signal
    -
    -

    - On Windows, - the CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, - and CTRL_SHUTDOWN_EVENT events now generate - a syscall.SIGTERM signal, similar to how Control-C - and Control-Break generate a syscall.SIGINT signal. -

    -
    -
    - -
    plugin
    -
    -

    - The plugin package now supports freebsd/amd64. -

    -
    -
    - -
    reflect
    -
    -

    - StructOf now - supports creating struct types with unexported fields, by - setting the PkgPath field in - a StructField element. -

    -
    -
    - -
    runtime
    -
    -

    - runtime.Goexit can no longer be aborted by a - recursive panic/recover. -

    - -

    - On macOS, SIGPIPE is no longer forwarded to signal - handlers installed before the Go runtime is initialized. - This is necessary because macOS delivers SIGPIPE - to the main thread - rather than the thread writing to the closed pipe. -

    -
    -
    - -
    runtime/pprof
    -
    -

    - The generated profile no longer includes the pseudo-PCs used for inline - marks. Symbol information of inlined functions is encoded in - the format - the pprof tool expects. This is a fix for the regression introduced - during recent releases. -

    -
    -
    - -
    strconv
    -
    -

    - The NumError - type now has - an Unwrap - method that may be used to retrieve the reason that a conversion - failed. - This supports using NumError values - with errors.Is to see - if the underlying error - is strconv.ErrRange - or strconv.ErrSyntax. -

    -
    -
    - -
    sync
    -
    -

    - Unlocking a highly contended Mutex now directly - yields the CPU to the next goroutine waiting for - that Mutex. This significantly improves the - performance of highly contended mutexes on high CPU count - machines. -

    -
    -
    - -
    testing
    -
    -

    - The testing package now supports cleanup functions, called after - a test or benchmark has finished, by calling - T.Cleanup or - B.Cleanup respectively. -

    -
    -
    - -
    text/template
    -
    -

    - The text/template package now correctly reports errors when a - parenthesized argument is used as a function. - This most commonly shows up in erroneous cases like - {{if (eq .F "a") or (eq .F "b")}}. - This should be written as {{if or (eq .F "a") (eq .F "b")}}. - The erroneous case never worked as expected, and will now be - reported with an error can't give argument to non-function. -

    -
    -
    - -
    unicode
    -
    -

    - The unicode package and associated - support throughout the system has been upgraded from Unicode 11.0 to - Unicode 12.0, - which adds 554 new characters, including four new scripts, and 61 new emoji. -

    -
    -
    diff --git a/doc/go1.15.html b/doc/go1.15.html deleted file mode 100644 index c9997c0ca3..0000000000 --- a/doc/go1.15.html +++ /dev/null @@ -1,1064 +0,0 @@ - - - - - - -

    Introduction to Go 1.15

    - -

    - The latest Go release, version 1.15, arrives six months after Go 1.14. - Most of its changes are in the implementation of the toolchain, runtime, and libraries. - As always, the release maintains the Go 1 promise of compatibility. - We expect almost all Go programs to continue to compile and run as before. -

    - -

    - Go 1.15 includes substantial improvements to the linker, - improves allocation for small objects at high core counts, and - deprecates X.509 CommonName. - GOPROXY now supports skipping proxies that return errors and - a new embedded tzdata package has been added. -

    - -

    Changes to the language

    - -

    - There are no changes to the language. -

    - -

    Ports

    - -

    Darwin

    - -

    - As announced in the Go 1.14 release - notes, Go 1.15 requires macOS 10.12 Sierra or later; support for - previous versions has been discontinued. -

    - -

    - As announced in the Go 1.14 release - notes, Go 1.15 drops support for 32-bit binaries on macOS, iOS, - iPadOS, watchOS, and tvOS (the darwin/386 - and darwin/arm ports). Go continues to support the - 64-bit darwin/amd64 and darwin/arm64 ports. -

    - -

    Windows

    - -

    - Go now generates Windows ASLR executables when -buildmode=pie - cmd/link flag is provided. Go command uses -buildmode=pie - by default on Windows. -

    - -

    - The -race and -msan flags now always - enable -d=checkptr, which checks uses - of unsafe.Pointer. This was previously the case on all - OSes except Windows. -

    - -

    - Go-built DLLs no longer cause the process to exit when it receives a - signal (such as Ctrl-C at a terminal). -

    - -

    Android

    - -

    - When linking binaries for Android, Go 1.15 explicitly selects - the lld linker available in recent versions of the NDK. - The lld linker avoids crashes on some devices, and is - planned to become the default NDK linker in a future NDK version. -

    - -

    OpenBSD

    - -

    - Go 1.15 adds support for OpenBSD 6.7 on GOARCH=arm - and GOARCH=arm64. Previous versions of Go already - supported OpenBSD 6.7 on GOARCH=386 - and GOARCH=amd64. -

    - -

    RISC-V

    - -

    - There has been progress in improving the stability and performance - of the 64-bit RISC-V port on Linux (GOOS=linux, - GOARCH=riscv64). It also now supports asynchronous - preemption. -

    - -

    386

    - -

    - Go 1.15 is the last release to support x87-only floating-point - hardware (GO386=387). Future releases will require at - least SSE2 support on 386, raising Go's - minimum GOARCH=386 requirement to the Intel Pentium 4 - (released in 2000) or AMD Opteron/Athlon 64 (released in 2003). -

    - -

    Tools

    - -

    Go command

    - -

    - The GOPROXY environment variable now supports skipping proxies - that return errors. Proxy URLs may now be separated with either commas - (,) or pipe characters (|). If a proxy URL is - followed by a comma, the go command will only try the next proxy - in the list after a 404 or 410 HTTP response. If a proxy URL is followed by a - pipe character, the go command will try the next proxy in the - list after any error. Note that the default value of GOPROXY - remains https://proxy.golang.org,direct, which does not fall - back to direct in case of errors. -

    - -

    go test

    - -

    - Changing the -timeout flag now invalidates cached test results. A - cached result for a test run with a long timeout will no longer count as - passing when go test is re-invoked with a short one. -

    - -

    Flag parsing

    - -

    - Various flag parsing issues in go test and - go vet have been fixed. Notably, flags specified - in GOFLAGS are handled more consistently, and - the -outputdir flag now interprets relative paths relative to the - working directory of the go command (rather than the working - directory of each individual test). -

    - -

    Module cache

    - -

    - The location of the module cache may now be set with - the GOMODCACHE environment variable. The default value of - GOMODCACHE is GOPATH[0]/pkg/mod, the location of the - module cache before this change. -

    - -

    - A workaround is now available for Windows "Access is denied" errors in - go commands that access the module cache, caused by external - programs concurrently scanning the file system (see - issue #36568). The workaround is - not enabled by default because it is not safe to use when Go versions lower - than 1.14.2 and 1.13.10 are running concurrently with the same module cache. - It can be enabled by explicitly setting the environment variable - GODEBUG=modcacheunzipinplace=1. -

    - -

    Vet

    - -

    New warning for string(x)

    - -

    - The vet tool now warns about conversions of the - form string(x) where x has an integer type - other than rune or byte. - Experience with Go has shown that many conversions of this form - erroneously assume that string(x) evaluates to the - string representation of the integer x. - It actually evaluates to a string containing the UTF-8 encoding of - the value of x. - For example, string(9786) does not evaluate to the - string "9786"; it evaluates to the - string "\xe2\x98\xba", or "☺". -

    - -

    - Code that is using string(x) correctly can be rewritten - to string(rune(x)). - Or, in some cases, calling utf8.EncodeRune(buf, x) with - a suitable byte slice buf may be the right solution. - Other code should most likely use strconv.Itoa - or fmt.Sprint. -

    - -

    - This new vet check is enabled by default when - using go test. -

    - -

    - We are considering prohibiting the conversion in a future release of Go. - That is, the language would change to only - permit string(x) for integer x when the - type of x is rune or byte. - Such a language change would not be backward compatible. - We are using this vet check as a first trial step toward changing - the language. -

    - -

    New warning for impossible interface conversions

    - -

    - The vet tool now warns about type assertions from one interface type - to another interface type when the type assertion will always fail. - This will happen if both interface types implement a method with the - same name but with a different type signature. -

    - -

    - There is no reason to write a type assertion that always fails, so - any code that triggers this vet check should be rewritten. -

    - -

    - This new vet check is enabled by default when - using go test. -

    - -

    - We are considering prohibiting impossible interface type assertions - in a future release of Go. - Such a language change would not be backward compatible. - We are using this vet check as a first trial step toward changing - the language. -

    - -

    Runtime

    - -

    - If panic is invoked with a value whose type is derived from any - of: bool, complex64, complex128, float32, float64, - int, int8, int16, int32, int64, string, - uint, uint8, uint16, uint32, uint64, uintptr, - then the value will be printed, instead of just its address. - Previously, this was only true for values of exactly these types. -

    - -

    - On a Unix system, if the kill command - or kill system call is used to send - a SIGSEGV, SIGBUS, - or SIGFPE signal to a Go program, and if the signal - is not being handled via - os/signal.Notify, - the Go program will now reliably crash with a stack trace. - In earlier releases the behavior was unpredictable. -

    - -

    - Allocation of small objects now performs much better at high core - counts, and has lower worst-case latency. -

    - -

    - Converting a small integer value into an interface value no longer - causes allocation. -

    - -

    - Non-blocking receives on closed channels now perform as well as - non-blocking receives on open channels. -

    - -

    Compiler

    - -

    - Package unsafe's safety - rules allow converting an unsafe.Pointer - into uintptr when calling certain - functions. Previously, in some cases, the compiler allowed multiple - chained conversions (for example, syscall.Syscall(…, - uintptr(uintptr(ptr)), …)). The compiler - now requires exactly one conversion. Code that used multiple - conversions should be updated to satisfy the safety rules. -

    - -

    - Go 1.15 reduces typical binary sizes by around 5% compared to Go - 1.14 by eliminating certain types of GC metadata and more - aggressively eliminating unused type metadata. -

    - -

    - The toolchain now mitigates - Intel - CPU erratum SKX102 on GOARCH=amd64 by aligning - functions to 32 byte boundaries and padding jump instructions. While - this padding increases binary sizes, this is more than made up for - by the binary size improvements mentioned above. -

    - -

    - Go 1.15 adds a -spectre flag to both the - compiler and the assembler, to allow enabling Spectre mitigations. - These should almost never be needed and are provided mainly as a - “defense in depth” mechanism. - See the Spectre wiki page for details. -

    - -

    - The compiler now rejects //go: compiler directives that - have no meaning for the declaration they are applied to with a - "misplaced compiler directive" error. Such misapplied directives - were broken before, but were silently ignored by the compiler. -

    - -

    - The compiler's -json optimization logging now reports - large (>= 128 byte) copies and includes explanations of escape - analysis decisions. -

    - -

    Linker

    - -

    - This release includes substantial improvements to the Go linker, - which reduce linker resource usage (both time and memory) and - improve code robustness/maintainability. -

    - -

    - For a representative set of large Go programs, linking is 20% faster - and requires 30% less memory on average, for ELF-based - OSes (Linux, FreeBSD, NetBSD, OpenBSD, Dragonfly, and Solaris) - running on amd64 architectures, with more modest - improvements for other architecture/OS combinations. -

    - -

    - The key contributors to better linker performance are a newly - redesigned object file format, and a revamping of internal - phases to increase concurrency (for example, applying relocations to - symbols in parallel). Object files in Go 1.15 are slightly larger - than their 1.14 equivalents. -

    - -

    - These changes are part of a multi-release project - to modernize the Go - linker, meaning that there will be additional linker - improvements expected in future releases. -

    - -

    - The linker now defaults to internal linking mode - for -buildmode=pie on - linux/amd64 and linux/arm64, so these - configurations no longer require a C linker. External linking - mode (which was the default in Go 1.14 for - -buildmode=pie) can still be requested with - -ldflags=-linkmode=external flag. -

    - -

    Objdump

    - -

    - The objdump tool now supports - disassembling in GNU assembler syntax with the -gnu - flag. -

    - -

    Core library

    - -

    New embedded tzdata package

    - -

    - Go 1.15 includes a new package, - time/tzdata, - that permits embedding the timezone database into a program. - Importing this package (as import _ "time/tzdata") - permits the program to find timezone information even if the - timezone database is not available on the local system. - You can also embed the timezone database by building - with -tags timetzdata. - Either approach increases the size of the program by about 800 KB. -

    - -

    Cgo

    - -

    - Go 1.15 will translate the C type EGLConfig to the - Go type uintptr. This change is similar to how Go - 1.12 and newer treats EGLDisplay, Darwin's CoreFoundation and - Java's JNI types. See the cgo - documentation for more information. -

    - -

    - In Go 1.15.3 and later, cgo will not permit Go code to allocate an - undefined struct type (a C struct defined as just struct - S; or similar) on the stack or heap. - Go code will only be permitted to use pointers to those types. - Allocating an instance of such a struct and passing a pointer, or a - full struct value, to C code was always unsafe and unlikely to work - correctly; it is now forbidden. - The fix is to either rewrite the Go code to use only pointers, or to - ensure that the Go code sees the full definition of the struct by - including the appropriate C header file. -

    - -

    X.509 CommonName deprecation

    - -

    - The deprecated, legacy behavior of treating the CommonName - field on X.509 certificates as a host name when no Subject Alternative Names - are present is now disabled by default. It can be temporarily re-enabled by - adding the value x509ignoreCN=0 to the GODEBUG - environment variable. -

    - -

    - Note that if the CommonName is an invalid host name, it's always - ignored, regardless of GODEBUG settings. Invalid names include - those with any characters other than letters, digits, hyphens and underscores, - and those with empty labels or trailing dots. -

    - -

    Minor changes to the library

    - -

    - As always, there are various minor changes and updates to the library, - made with the Go 1 promise of compatibility - in mind. -

    - -
    bufio
    -
    -

    - When a Scanner is - used with an invalid - io.Reader that - incorrectly returns a negative number from Read, - the Scanner will no longer panic, but will instead - return the new error - ErrBadReadCount. -

    -
    -
    - -
    context
    -
    -

    - Creating a derived Context using a nil parent is now explicitly - disallowed. Any attempt to do so with the - WithValue, - WithDeadline, or - WithCancel functions - will cause a panic. -

    -
    -
    - -
    crypto
    -
    -

    - The PrivateKey and PublicKey types in the - crypto/rsa, - crypto/ecdsa, and - crypto/ed25519 packages - now have an Equal method to compare keys for equivalence - or to make type-safe interfaces for public keys. The method signature - is compatible with - go-cmp's - definition of equality. -

    - -

    - Hash now implements - fmt.Stringer. -

    -
    -
    - -
    crypto/ecdsa
    -
    -

    - The new SignASN1 - and VerifyASN1 - functions allow generating and verifying ECDSA signatures in the standard - ASN.1 DER encoding. -

    -
    -
    - -
    crypto/elliptic
    -
    -

    - The new MarshalCompressed - and UnmarshalCompressed - functions allow encoding and decoding NIST elliptic curve points in compressed format. -

    -
    -
    - -
    crypto/rsa
    -
    -

    - VerifyPKCS1v15 - now rejects invalid short signatures with missing leading zeroes, according to RFC 8017. -

    -
    -
    - -
    crypto/tls
    -
    -

    - The new - Dialer - type and its - DialContext - method permit using a context to both connect and handshake with a TLS server. -

    - -

    - The new - VerifyConnection - callback on the Config type - allows custom verification logic for every connection. It has access to the - ConnectionState - which includes peer certificates, SCTs, and stapled OCSP responses. -

    - -

    - Auto-generated session ticket keys are now automatically rotated every 24 hours, - with a lifetime of 7 days, to limit their impact on forward secrecy. -

    - -

    - Session ticket lifetimes in TLS 1.2 and earlier, where the session keys - are reused for resumed connections, are now limited to 7 days, also to - limit their impact on forward secrecy. -

    - -

    - The client-side downgrade protection checks specified in RFC 8446 are now - enforced. This has the potential to cause connection errors for clients - encountering middleboxes that behave like unauthorized downgrade attacks. -

    - -

    - SignatureScheme, - CurveID, and - ClientAuthType - now implement fmt.Stringer. -

    - -

    - The ConnectionState - fields OCSPResponse and SignedCertificateTimestamps - are now repopulated on client-side resumed connections. -

    - -

    - tls.Conn - now returns an opaque error on permanently broken connections, wrapping - the temporary - net.Error. To access the - original net.Error, use - errors.As (or - errors.Unwrap) instead of a - type assertion. -

    -
    -
    - -
    crypto/x509
    -
    -

    - If either the name on the certificate or the name being verified (with - VerifyOptions.DNSName - or VerifyHostname) - are invalid, they will now be compared case-insensitively without further - processing (without honoring wildcards or stripping trailing dots). - Invalid names include those with any characters other than letters, - digits, hyphens and underscores, those with empty labels, and names on - certificates with trailing dots. -

    - -

    - The new CreateRevocationList - function and RevocationList type - allow creating RFC 5280-compliant X.509 v2 Certificate Revocation Lists. -

    - -

    - CreateCertificate - now automatically generates the SubjectKeyId if the template - is a CA and doesn't explicitly specify one. -

    - -

    - CreateCertificate - now returns an error if the template specifies MaxPathLen but is not a CA. -

    - -

    - On Unix systems other than macOS, the SSL_CERT_DIR - environment variable can now be a colon-separated list. -

    - -

    - On macOS, binaries are now always linked against - Security.framework to extract the system trust roots, - regardless of whether cgo is available. The resulting behavior should be - more consistent with the OS verifier. -

    -
    -
    - -
    crypto/x509/pkix
    -
    -

    - Name.String - now prints non-standard attributes from - Names if - ExtraNames is nil. -

    -
    -
    - -
    database/sql
    -
    -

    - The new DB.SetConnMaxIdleTime - method allows removing a connection from the connection pool after - it has been idle for a period of time, without regard to the total - lifespan of the connection. The DBStats.MaxIdleTimeClosed - field shows the total number of connections closed due to - DB.SetConnMaxIdleTime. -

    - -

    - The new Row.Err getter - allows checking for query errors without calling - Row.Scan. -

    -
    -
    - -
    database/sql/driver
    -
    -

    - The new Validator - interface may be implemented by Conn to allow drivers - to signal if a connection is valid or if it should be discarded. -

    -
    -
    - -
    debug/pe
    -
    -

    - The package now defines the - IMAGE_FILE, IMAGE_SUBSYSTEM, - and IMAGE_DLLCHARACTERISTICS constants used by the - PE file format. -

    -
    -
    - -
    encoding/asn1
    -
    -

    - Marshal now sorts the components - of SET OF according to X.690 DER. -

    - -

    - Unmarshal now rejects tags and - Object Identifiers which are not minimally encoded according to X.690 DER. -

    -
    -
    - -
    encoding/json
    -
    -

    - The package now has an internal limit to the maximum depth of - nesting when decoding. This reduces the possibility that a - deeply nested input could use large quantities of stack memory, - or even cause a "goroutine stack exceeds limit" panic. -

    -
    -
    - -
    flag
    -
    -

    - When the flag package sees -h or -help, - and those flags are not defined, it now prints a usage message. - If the FlagSet was created with - ExitOnError, - FlagSet.Parse would then - exit with a status of 2. In this release, the exit status for -h - or -help has been changed to 0. In particular, this applies to - the default handling of command line flags. -

    -
    -
    - -
    fmt
    -
    -

    - The printing verbs %#g and %#G now preserve - trailing zeros for floating-point values. -

    -
    -
    - -
    go/format
    -
    -

    - The Source and - Node functions - now canonicalize number literal prefixes and exponents as part - of formatting Go source code. This matches the behavior of the - gofmt command as it - was implemented since Go 1.13. -

    -
    -
    - -
    html/template
    -
    -

    - The package now uses Unicode escapes (\uNNNN) in all - JavaScript and JSON contexts. This fixes escaping errors in - application/ld+json and application/json - contexts. -

    -
    -
    - -
    io/ioutil
    -
    -

    - TempDir and - TempFile - now reject patterns that contain path separators. - That is, calls such as ioutil.TempFile("/tmp", "../base*") will no longer succeed. - This prevents unintended directory traversal. -

    -
    -
    - -
    math/big
    -
    -

    - The new Int.FillBytes - method allows serializing to fixed-size pre-allocated byte slices. -

    -
    -
    - -
    math/cmplx
    -
    -

    - The functions in this package were updated to conform to the C99 standard - (Annex G IEC 60559-compatible complex arithmetic) with respect to handling - of special arguments such as infinity, NaN and signed zero. -

    -
    -
    - -
    net
    -
    -

    - If an I/O operation exceeds a deadline set by - the Conn.SetDeadline, - Conn.SetReadDeadline, - or Conn.SetWriteDeadline methods, it will now - return an error that is or wraps - os.ErrDeadlineExceeded. - This may be used to reliably detect whether an error is due to - an exceeded deadline. - Earlier releases recommended calling the Timeout - method on the error, but I/O operations can return errors for - which Timeout returns true although a - deadline has not been exceeded. -

    - -

    - The new Resolver.LookupIP - method supports IP lookups that are both network-specific and accept a context. -

    -
    -
    - -
    net/http
    -
    -

    - Parsing is now stricter as a hardening measure against request smuggling attacks: - non-ASCII white space is no longer trimmed like SP and HTAB, and support for the - "identity" Transfer-Encoding was dropped. -

    -
    -
    - -
    net/http/httputil
    -
    -

    - ReverseProxy - now supports not modifying the X-Forwarded-For - header when the incoming Request.Header map entry - for that field is nil. -

    - -

    - When a Switching Protocol (like WebSocket) request handled by - ReverseProxy - is canceled, the backend connection is now correctly closed. -

    -
    -
    - -
    net/http/pprof
    -
    -

    - All profile endpoints now support a "seconds" parameter. When present, - the endpoint profiles for the specified number of seconds and reports the difference. - The meaning of the "seconds" parameter in the cpu profile and - the trace endpoints is unchanged. -

    -
    -
    - -
    net/url
    -
    -

    - The new URL field - RawFragment and method EscapedFragment - provide detail about and control over the exact encoding of a particular fragment. - These are analogous to - RawPath and EscapedPath. -

    -

    - The new URL - method Redacted - returns the URL in string form with any password replaced with xxxxx. -

    -
    -
    - -
    os
    -
    -

    - If an I/O operation exceeds a deadline set by - the File.SetDeadline, - File.SetReadDeadline, - or File.SetWriteDeadline - methods, it will now return an error that is or wraps - os.ErrDeadlineExceeded. - This may be used to reliably detect whether an error is due to - an exceeded deadline. - Earlier releases recommended calling the Timeout - method on the error, but I/O operations can return errors for - which Timeout returns true although a - deadline has not been exceeded. -

    - -

    - Packages os and net now automatically - retry system calls that fail with EINTR. Previously - this led to spurious failures, which became more common in Go - 1.14 with the addition of asynchronous preemption. Now this is - handled transparently. -

    - -

    - The os.File type now - supports a ReadFrom - method. This permits the use of the copy_file_range - system call on some systems when using - io.Copy to copy data - from one os.File to another. A consequence is that - io.CopyBuffer - will not always use the provided buffer when copying to a - os.File. If a program wants to force the use of - the provided buffer, it can be done by writing - io.CopyBuffer(struct{ io.Writer }{dst}, src, buf). -

    -
    -
    - -
    plugin
    -
    -

    - DWARF generation is now supported (and enabled by default) for -buildmode=plugin on macOS. -

    -
    -
    -

    - Building with -buildmode=plugin is now supported on freebsd/amd64. -

    -
    -
    - -
    reflect
    -
    -

    - Package reflect now disallows accessing methods of all - non-exported fields, whereas previously it allowed accessing - those of non-exported, embedded fields. Code that relies on the - previous behavior should be updated to instead access the - corresponding promoted method of the enclosing variable. -

    -
    -
    - -
    regexp
    -
    -

    - The new Regexp.SubexpIndex - method returns the index of the first subexpression with the given name - within the regular expression. -

    -
    -
    - -
    runtime
    -
    -

    - Several functions, including - ReadMemStats - and - GoroutineProfile, - no longer block if a garbage collection is in progress. -

    -
    -
    - -
    runtime/pprof
    -
    -

    - The goroutine profile now includes the profile labels associated with each - goroutine at the time of profiling. This feature is not yet implemented for - the profile reported with debug=2. -

    -
    -
    - -
    strconv
    -
    -

    - FormatComplex and ParseComplex are added for working with complex numbers. -

    -

    - FormatComplex converts a complex number into a string of the form (a+bi), where a and b are the real and imaginary parts. -

    -

    - ParseComplex converts a string into a complex number of a specified precision. ParseComplex accepts complex numbers in the format N+Ni. -

    -
    -
    - -
    sync
    -
    -

    - The new method - Map.LoadAndDelete - atomically deletes a key and returns the previous value if present. -

    -

    - The method - Map.Delete - is more efficient. -

    -
    -
    - -
    syscall
    -
    -

    - On Unix systems, functions that use - SysProcAttr - will now reject attempts to set both the Setctty - and Foreground fields, as they both use - the Ctty field but do so in incompatible ways. - We expect that few existing programs set both fields. -

    -

    - Setting the Setctty field now requires that the - Ctty field be set to a file descriptor number in the - child process, as determined by the ProcAttr.Files field. - Using a child descriptor always worked, but there were certain - cases where using a parent file descriptor also happened to work. - Some programs that set Setctty will need to change - the value of Ctty to use a child descriptor number. -

    - -

    - It is now possible to call - system calls that return floating point values - on windows/amd64. -

    -
    -
    - -
    testing
    -
    -

    - The testing.T type now has a - Deadline method - that reports the time at which the test binary will have exceeded its - timeout. -

    - -

    - A TestMain function is no longer required to call - os.Exit. If a TestMain function returns, - the test binary will call os.Exit with the value returned - by m.Run. -

    - -

    - The new methods - T.TempDir and - B.TempDir - return temporary directories that are automatically cleaned up - at the end of the test. -

    - -

    - go test -v now groups output by - test name, rather than printing the test name on each line. -

    -
    -
    - -
    text/template
    -
    -

    - JSEscape now - consistently uses Unicode escapes (\u00XX), which are - compatible with JSON. -

    -
    -
    - -
    time
    -
    -

    - The new method - Ticker.Reset - supports changing the duration of a ticker. -

    - -

    - When returning an error, ParseDuration now quotes the original value. -

    -
    -
    diff --git a/doc/go1.2.html b/doc/go1.2.html deleted file mode 100644 index 1f6051418c..0000000000 --- a/doc/go1.2.html +++ /dev/null @@ -1,979 +0,0 @@ - - -

    Introduction to Go 1.2

    - -

    -Since the release of Go version 1.1 in April, 2013, -the release schedule has been shortened to make the release process more efficient. -This release, Go version 1.2 or Go 1.2 for short, arrives roughly six months after 1.1, -while 1.1 took over a year to appear after 1.0. -Because of the shorter time scale, 1.2 is a smaller delta than the step from 1.0 to 1.1, -but it still has some significant developments, including -a better scheduler and one new language feature. -Of course, Go 1.2 keeps the promise -of compatibility. -The overwhelming majority of programs built with Go 1.1 (or 1.0 for that matter) -will run without any changes whatsoever when moved to 1.2, -although the introduction of one restriction -to a corner of the language may expose already-incorrect code -(see the discussion of the use of nil). -

    - -

    Changes to the language

    - -

    -In the interest of firming up the specification, one corner case has been clarified, -with consequences for programs. -There is also one new language feature. -

    - -

    Use of nil

    - -

    -The language now specifies that, for safety reasons, -certain uses of nil pointers are guaranteed to trigger a run-time panic. -For instance, in Go 1.0, given code like -

    - -
    -type T struct {
    -    X [1<<24]byte
    -    Field int32
    -}
    -
    -func main() {
    -    var x *T
    -    ...
    -}
    -
    - -

    -the nil pointer x could be used to access memory incorrectly: -the expression x.Field could access memory at address 1<<24. -To prevent such unsafe behavior, in Go 1.2 the compilers now guarantee that any indirection through -a nil pointer, such as illustrated here but also in nil pointers to arrays, nil interface values, -nil slices, and so on, will either panic or return a correct, safe non-nil value. -In short, any expression that explicitly or implicitly requires evaluation of a nil address is an error. -The implementation may inject extra tests into the compiled program to enforce this behavior. -

    - -

    -Further details are in the -design document. -

    - -

    -Updating: -Most code that depended on the old behavior is erroneous and will fail when run. -Such programs will need to be updated by hand. -

    - -

    Three-index slices

    - -

    -Go 1.2 adds the ability to specify the capacity as well as the length when using a slicing operation -on an existing array or slice. -A slicing operation creates a new slice by describing a contiguous section of an already-created array or slice: -

    - -
    -var array [10]int
    -slice := array[2:4]
    -
    - -

    -The capacity of the slice is the maximum number of elements that the slice may hold, even after reslicing; -it reflects the size of the underlying array. -In this example, the capacity of the slice variable is 8. -

    - -

    -Go 1.2 adds new syntax to allow a slicing operation to specify the capacity as well as the length. -A second -colon introduces the capacity value, which must be less than or equal to the capacity of the -source slice or array, adjusted for the origin. For instance, -

    - -
    -slice = array[2:4:7]
    -
    - -

    -sets the slice to have the same length as in the earlier example but its capacity is now only 5 elements (7-2). -It is impossible to use this new slice value to access the last three elements of the original array. -

    - -

    -In this three-index notation, a missing first index ([:i:j]) defaults to zero but the other -two indices must always be specified explicitly. -It is possible that future releases of Go may introduce default values for these indices. -

    - -

    -Further details are in the -design document. -

    - -

    -Updating: -This is a backwards-compatible change that affects no existing programs. -

    - -

    Changes to the implementations and tools

    - -

    Pre-emption in the scheduler

    - -

    -In prior releases, a goroutine that was looping forever could starve out other -goroutines on the same thread, a serious problem when GOMAXPROCS -provided only one user thread. -In Go 1.2, this is partially addressed: The scheduler is invoked occasionally -upon entry to a function. -This means that any loop that includes a (non-inlined) function call can -be pre-empted, allowing other goroutines to run on the same thread. -

    - -

    Limit on the number of threads

    - -

    -Go 1.2 introduces a configurable limit (default 10,000) to the total number of threads -a single program may have in its address space, to avoid resource starvation -issues in some environments. -Note that goroutines are multiplexed onto threads so this limit does not directly -limit the number of goroutines, only the number that may be simultaneously blocked -in a system call. -In practice, the limit is hard to reach. -

    - -

    -The new SetMaxThreads function in the -runtime/debug package controls the thread count limit. -

    - -

    -Updating: -Few functions will be affected by the limit, but if a program dies because it hits the -limit, it could be modified to call SetMaxThreads to set a higher count. -Even better would be to refactor the program to need fewer threads, reducing consumption -of kernel resources. -

    - -

    Stack size

    - -

    -In Go 1.2, the minimum size of the stack when a goroutine is created has been lifted from 4KB to 8KB. -Many programs were suffering performance problems with the old size, which had a tendency -to introduce expensive stack-segment switching in performance-critical sections. -The new number was determined by empirical testing. -

    - -

    -At the other end, the new function SetMaxStack -in the runtime/debug package controls -the maximum size of a single goroutine's stack. -The default is 1GB on 64-bit systems and 250MB on 32-bit systems. -Before Go 1.2, it was too easy for a runaway recursion to consume all the memory on a machine. -

    - -

    -Updating: -The increased minimum stack size may cause programs with many goroutines to use -more memory. There is no workaround, but plans for future releases -include new stack management technology that should address the problem better. -

    - -

    Cgo and C++

    - -

    -The cgo command will now invoke the C++ -compiler to build any pieces of the linked-to library that are written in C++; -the documentation has more detail. -

    - -

    Godoc and vet moved to the go.tools subrepository

    - -

    -Both binaries are still included with the distribution, but the source code for the -godoc and vet commands has moved to the -go.tools subrepository. -

    - -

    -Also, the core of the godoc program has been split into a -library, -while the command itself is in a separate -directory. -The move allows the code to be updated easily and the separation into a library and command -makes it easier to construct custom binaries for local sites and different deployment methods. -

    - -

    -Updating: -Since godoc and vet are not part of the library, -no client Go code depends on the their source and no updating is required. -

    - -

    -The binary distributions available from golang.org -include these binaries, so users of these distributions are unaffected. -

    - -

    -When building from source, users must use "go get" to install godoc and vet. -(The binaries will continue to be installed in their usual locations, not -$GOPATH/bin.) -

    - -
    -$ go get code.google.com/p/go.tools/cmd/godoc
    -$ go get code.google.com/p/go.tools/cmd/vet
    -
    - -

    Status of gccgo

    - -

    -We expect the future GCC 4.9 release to include gccgo with full -support for Go 1.2. -In the current (4.8.2) release of GCC, gccgo implements Go 1.1.2. -

    - -

    Changes to the gc compiler and linker

    - -

    -Go 1.2 has several semantic changes to the workings of the gc compiler suite. -Most users will be unaffected by them. -

    - -

    -The cgo command now -works when C++ is included in the library being linked against. -See the cgo documentation -for details. -

    - -

    -The gc compiler displayed a vestigial detail of its origins when -a program had no package clause: it assumed -the file was in package main. -The past has been erased, and a missing package clause -is now an error. -

    - -

    -On the ARM, the toolchain supports "external linking", which -is a step towards being able to build shared libraries with the gc -toolchain and to provide dynamic linking support for environments -in which that is necessary. -

    - -

    -In the runtime for the ARM, with 5a, it used to be possible to refer -to the runtime-internal m (machine) and g -(goroutine) variables using R9 and R10 directly. -It is now necessary to refer to them by their proper names. -

    - -

    -Also on the ARM, the 5l linker (sic) now defines the -MOVBS and MOVHS instructions -as synonyms of MOVB and MOVH, -to make clearer the separation between signed and unsigned -sub-word moves; the unsigned versions already existed with a -U suffix. -

    - -

    Test coverage

    - -

    -One major new feature of go test is -that it can now compute and, with help from a new, separately installed -"go tool cover" program, display test coverage results. -

    - -

    -The cover tool is part of the -go.tools -subrepository. -It can be installed by running -

    - -
    -$ go get code.google.com/p/go.tools/cmd/cover
    -
    - -

    -The cover tool does two things. -First, when "go test" is given the -cover flag, it is run automatically -to rewrite the source for the package and insert instrumentation statements. -The test is then compiled and run as usual, and basic coverage statistics are reported: -

    - -
    -$ go test -cover fmt
    -ok  	fmt	0.060s	coverage: 91.4% of statements
    -$
    -
    - -

    -Second, for more detailed reports, different flags to "go test" can create a coverage profile file, -which the cover program, invoked with "go tool cover", can then analyze. -

    - -

    -Details on how to generate and analyze coverage statistics can be found by running the commands -

    - -
    -$ go help testflag
    -$ go tool cover -help
    -
    - -

    The go doc command is deleted

    - -

    -The "go doc" command is deleted. -Note that the godoc tool itself is not deleted, -just the wrapping of it by the go command. -All it did was show the documents for a package by package path, -which godoc itself already does with more flexibility. -It has therefore been deleted to reduce the number of documentation tools and, -as part of the restructuring of godoc, encourage better options in future. -

    - -

    -Updating: For those who still need the precise functionality of running -

    - -
    -$ go doc
    -
    - -

    -in a directory, the behavior is identical to running -

    - -
    -$ godoc .
    -
    - -

    Changes to the go command

    - -

    -The go get command -now has a -t flag that causes it to download the dependencies -of the tests run by the package, not just those of the package itself. -By default, as before, dependencies of the tests are not downloaded. -

    - -

    Performance

    - -

    -There are a number of significant performance improvements in the standard library; here are a few of them. -

    - -
      - -
    • -The compress/bzip2 -decompresses about 30% faster. -
    • - -
    • -The crypto/des package -is about five times faster. -
    • - -
    • -The encoding/json package -encodes about 30% faster. -
    • - -
    • -Networking performance on Windows and BSD systems is about 30% faster through the use -of an integrated network poller in the runtime, similar to what was done for Linux and OS X -in Go 1.1. -
    • - -
    - -

    Changes to the standard library

    - - -

    The archive/tar and archive/zip packages

    - -

    -The -archive/tar -and -archive/zip -packages have had a change to their semantics that may break existing programs. -The issue is that they both provided an implementation of the -os.FileInfo -interface that was not compliant with the specification for that interface. -In particular, their Name method returned the full -path name of the entry, but the interface specification requires that -the method return only the base name (final path element). -

    - -

    -Updating: Since this behavior was newly implemented and -a bit obscure, it is possible that no code depends on the broken behavior. -If there are programs that do depend on it, they will need to be identified -and fixed manually. -

    - -

    The new encoding package

    - -

    -There is a new package, encoding, -that defines a set of standard encoding interfaces that may be used to -build custom marshalers and unmarshalers for packages such as -encoding/xml, -encoding/json, -and -encoding/binary. -These new interfaces have been used to tidy up some implementations in -the standard library. -

    - -

    -The new interfaces are called -BinaryMarshaler, -BinaryUnmarshaler, -TextMarshaler, -and -TextUnmarshaler. -Full details are in the documentation for the package -and a separate design document. -

    - -

    The fmt package

    - -

    -The fmt package's formatted print -routines such as Printf -now allow the data items to be printed to be accessed in arbitrary order -by using an indexing operation in the formatting specifications. -Wherever an argument is to be fetched from the argument list for formatting, -either as the value to be formatted or as a width or specification integer, -a new optional indexing notation [n] -fetches argument n instead. -The value of n is 1-indexed. -After such an indexing operating, the next argument to be fetched by normal -processing will be n+1. -

    - -

    -For example, the normal Printf call -

    - -
    -fmt.Sprintf("%c %c %c\n", 'a', 'b', 'c')
    -
    - -

    -would create the string "a b c", but with indexing operations like this, -

    - -
    -fmt.Sprintf("%[3]c %[1]c %c\n", 'a', 'b', 'c')
    -
    - -

    -the result is ""c a b". The [3] index accesses the third formatting -argument, which is 'c', [1] accesses the first, 'a', -and then the next fetch accesses the argument following that one, 'b'. -

    - -

    -The motivation for this feature is programmable format statements to access -the arguments in different order for localization, but it has other uses: -

    - -
    -log.Printf("trace: value %v of type %[1]T\n", expensiveFunction(a.b[c]))
    -
    - -

    -Updating: The change to the syntax of format specifications -is strictly backwards compatible, so it affects no working programs. -

    - -

    The text/template and html/template packages

    - -

    -The -text/template package -has a couple of changes in Go 1.2, both of which are also mirrored in the -html/template package. -

    - -

    -First, there are new default functions for comparing basic types. -The functions are listed in this table, which shows their names and -the associated familiar comparison operator. -

    - - - - - - - - - - - - - - - - - - - - - - - -
    Name Operator
    eq ==
    ne !=
    lt <
    le <=
    gt >
    ge >=
    - -

    -These functions behave slightly differently from the corresponding Go operators. -First, they operate only on basic types (bool, int, -float64, string, etc.). -(Go allows comparison of arrays and structs as well, under some circumstances.) -Second, values can be compared as long as they are the same sort of value: -any signed integer value can be compared to any other signed integer value for example. (Go -does not permit comparing an int8 and an int16). -Finally, the eq function (only) allows comparison of the first -argument with one or more following arguments. The template in this example, -

    - -
    -{{"{{"}}if eq .A 1 2 3 {{"}}"}} equal {{"{{"}}else{{"}}"}} not equal {{"{{"}}end{{"}}"}}
    -
    - -

    -reports "equal" if .A is equal to any of 1, 2, or 3. -

    - -

    -The second change is that a small addition to the grammar makes "if else if" chains easier to write. -Instead of writing, -

    - -
    -{{"{{"}}if eq .A 1{{"}}"}} X {{"{{"}}else{{"}}"}} {{"{{"}}if eq .A 2{{"}}"}} Y {{"{{"}}end{{"}}"}} {{"{{"}}end{{"}}"}} 
    -
    - -

    -one can fold the second "if" into the "else" and have only one "end", like this: -

    - -
    -{{"{{"}}if eq .A 1{{"}}"}} X {{"{{"}}else if eq .A 2{{"}}"}} Y {{"{{"}}end{{"}}"}}
    -
    - -

    -The two forms are identical in effect; the difference is just in the syntax. -

    - -

    -Updating: Neither the "else if" change nor the comparison functions -affect existing programs. Those that -already define functions called eq and so on through a function -map are unaffected because the associated function map will override the new -default function definitions. -

    - -

    New packages

    - -

    -There are two new packages. -

    - - - -

    Minor changes to the library

    - -

    -The following list summarizes a number of minor changes to the library, mostly additions. -See the relevant package documentation for more information about each change. -

    - -
      - -
    • -The archive/zip package -adds the -DataOffset accessor -to return the offset of a file's (possibly compressed) data within the archive. -
    • - -
    • -The bufio package -adds Reset -methods to Reader and -Writer. -These methods allow the Readers -and Writers -to be re-used on new input and output readers and writers, saving -allocation overhead. -
    • - -
    • -The compress/bzip2 -can now decompress concatenated archives. -
    • - -
    • -The compress/flate -package adds a Reset -method on the Writer, -to make it possible to reduce allocation when, for instance, constructing an -archive to hold multiple compressed files. -
    • - -
    • -The compress/gzip package's -Writer type adds a -Reset -so it may be reused. -
    • - -
    • -The compress/zlib package's -Writer type adds a -Reset -so it may be reused. -
    • - -
    • -The container/heap package -adds a Fix -method to provide a more efficient way to update an item's position in the heap. -
    • - -
    • -The container/list package -adds the MoveBefore -and -MoveAfter -methods, which implement the obvious rearrangement. -
    • - -
    • -The crypto/cipher package -adds the a new GCM mode (Galois Counter Mode), which is almost always -used with AES encryption. -
    • - -
    • -The -crypto/md5 package -adds a new Sum function -to simplify hashing without sacrificing performance. -
    • - -
    • -Similarly, the -crypto/sha1 package -adds a new Sum function. -
    • - -
    • -Also, the -crypto/sha256 package -adds Sum256 -and Sum224 functions. -
    • - -
    • -Finally, the crypto/sha512 package -adds Sum512 and -Sum384 functions. -
    • - -
    • -The crypto/x509 package -adds support for reading and writing arbitrary extensions. -
    • - -
    • -The crypto/tls package adds -support for TLS 1.1, 1.2 and AES-GCM. -
    • - -
    • -The database/sql package adds a -SetMaxOpenConns -method on DB to limit the -number of open connections to the database. -
    • - -
    • -The encoding/csv package -now always allows trailing commas on fields. -
    • - -
    • -The encoding/gob package -now treats channel and function fields of structures as if they were unexported, -even if they are not. That is, it ignores them completely. Previously they would -trigger an error, which could cause unexpected compatibility problems if an -embedded structure added such a field. -The package also now supports the generic BinaryMarshaler and -BinaryUnmarshaler interfaces of the -encoding package -described above. -
    • - -
    • -The encoding/json package -now will always escape ampersands as "\u0026" when printing strings. -It will now accept but correct invalid UTF-8 in -Marshal -(such input was previously rejected). -Finally, it now supports the generic encoding interfaces of the -encoding package -described above. -
    • - -
    • -The encoding/xml package -now allows attributes stored in pointers to be marshaled. -It also supports the generic encoding interfaces of the -encoding package -described above through the new -Marshaler, -Unmarshaler, -and related -MarshalerAttr and -UnmarshalerAttr -interfaces. -The package also adds a -Flush method -to the -Encoder -type for use by custom encoders. See the documentation for -EncodeToken -to see how to use it. -
    • - -
    • -The flag package now -has a Getter interface -to allow the value of a flag to be retrieved. Due to the -Go 1 compatibility guidelines, this method cannot be added to the existing -Value -interface, but all the existing standard flag types implement it. -The package also now exports the CommandLine -flag set, which holds the flags from the command line. -
    • - -
    • -The go/ast package's -SliceExpr struct -has a new boolean field, Slice3, which is set to true -when representing a slice expression with three indices (two colons). -The default is false, representing the usual two-index form. -
    • - -
    • -The go/build package adds -the AllTags field -to the Package type, -to make it easier to process build tags. -
    • - -
    • -The image/draw package now -exports an interface, Drawer, -that wraps the standard Draw method. -The Porter-Duff operators now implement this interface, in effect binding an operation to -the draw operator rather than providing it explicitly. -Given a paletted image as its destination, the new -FloydSteinberg -implementation of the -Drawer -interface will use the Floyd-Steinberg error diffusion algorithm to draw the image. -To create palettes suitable for such processing, the new -Quantizer interface -represents implementations of quantization algorithms that choose a palette -given a full-color image. -There are no implementations of this interface in the library. -
    • - -
    • -The image/gif package -can now create GIF files using the new -Encode -and EncodeAll -functions. -Their options argument allows specification of an image -Quantizer to use; -if it is nil, the generated GIF will use the -Plan9 -color map (palette) defined in the new -image/color/palette package. -The options also specify a -Drawer -to use to create the output image; -if it is nil, Floyd-Steinberg error diffusion is used. -
    • - -
    • -The Copy method of the -io package now prioritizes its -arguments differently. -If one argument implements WriterTo -and the other implements ReaderFrom, -Copy will now invoke -WriterTo to do the work, -so that less intermediate buffering is required in general. -
    • - -
    • -The net package requires cgo by default -because the host operating system must in general mediate network call setup. -On some systems, though, it is possible to use the network without cgo, and useful -to do so, for instance to avoid dynamic linking. -The new build tag netgo (off by default) allows the construction of a -net package in pure Go on those systems where it is possible. -
    • - -
    • -The net package adds a new field -DualStack to the Dialer -struct for TCP connection setup using a dual IP stack as described in -RFC 6555. -
    • - -
    • -The net/http package will no longer -transmit cookies that are incorrect according to -RFC 6265. -It just logs an error and sends nothing. -Also, -the net/http package's -ReadResponse -function now permits the *Request parameter to be nil, -whereupon it assumes a GET request. -Finally, an HTTP server will now serve HEAD -requests transparently, without the need for special casing in handler code. -While serving a HEAD request, writes to a -Handler's -ResponseWriter -are absorbed by the -Server -and the client receives an empty body as required by the HTTP specification. -
    • - -
    • -The os/exec package's -Cmd.StdinPipe method -returns an io.WriteCloser, but has changed its concrete -implementation from *os.File to an unexported type that embeds -*os.File, and it is now safe to close the returned value. -Before Go 1.2, there was an unavoidable race that this change fixes. -Code that needs access to the methods of *os.File can use an -interface type assertion, such as wc.(interface{ Sync() error }). -
    • - -
    • -The runtime package relaxes -the constraints on finalizer functions in -SetFinalizer: the -actual argument can now be any type that is assignable to the formal type of -the function, as is the case for any normal function call in Go. -
    • - -
    • -The sort package has a new -Stable function that implements -stable sorting. It is less efficient than the normal sort algorithm, however. -
    • - -
    • -The strings package adds -an IndexByte -function for consistency with the bytes package. -
    • - -
    • -The sync/atomic package -adds a new set of swap functions that atomically exchange the argument with the -value stored in the pointer, returning the old value. -The functions are -SwapInt32, -SwapInt64, -SwapUint32, -SwapUint64, -SwapUintptr, -and -SwapPointer, -which swaps an unsafe.Pointer. -
    • - -
    • -The syscall package now implements -Sendfile for Darwin. -
    • - -
    • -The testing package -now exports the TB interface. -It records the methods in common with the -T -and -B types, -to make it easier to share code between tests and benchmarks. -Also, the -AllocsPerRun -function now quantizes the return value to an integer (although it -still has type float64), to round off any error caused by -initialization and make the result more repeatable. -
    • - -
    • -The text/template package -now automatically dereferences pointer values when evaluating the arguments -to "escape" functions such as "html", to bring the behavior of such functions -in agreement with that of other printing functions such as "printf". -
    • - -
    • -In the time package, the -Parse function -and -Format -method -now handle time zone offsets with seconds, such as in the historical -date "1871-01-01T05:33:02+00:34:08". -Also, pattern matching in the formats for those routines is stricter: a non-lowercase letter -must now follow the standard words such as "Jan" and "Mon". -
    • - -
    • -The unicode package -adds In, -a nicer-to-use but equivalent version of the original -IsOneOf, -to see whether a character is a member of a Unicode category. -
    • - -
    diff --git a/doc/go1.3.html b/doc/go1.3.html deleted file mode 100644 index 18b3ec65d2..0000000000 --- a/doc/go1.3.html +++ /dev/null @@ -1,608 +0,0 @@ - - -

    Introduction to Go 1.3

    - -

    -The latest Go release, version 1.3, arrives six months after 1.2, -and contains no language changes. -It focuses primarily on implementation work, providing -precise garbage collection, -a major refactoring of the compiler toolchain that results in -faster builds, especially for large projects, -significant performance improvements across the board, -and support for DragonFly BSD, Solaris, Plan 9 and Google's Native Client architecture (NaCl). -It also has an important refinement to the memory model regarding synchronization. -As always, Go 1.3 keeps the promise -of compatibility, -and almost everything -will continue to compile and run without change when moved to 1.3. -

    - -

    Changes to the supported operating systems and architectures

    - -

    Removal of support for Windows 2000

    - -

    -Microsoft stopped supporting Windows 2000 in 2010. -Since it has implementation difficulties -regarding exception handling (signals in Unix terminology), -as of Go 1.3 it is not supported by Go either. -

    - -

    Support for DragonFly BSD

    - -

    -Go 1.3 now includes experimental support for DragonFly BSD on the amd64 (64-bit x86) and 386 (32-bit x86) architectures. -It uses DragonFly BSD 3.6 or above. -

    - -

    Support for FreeBSD

    - -

    -It was not announced at the time, but since the release of Go 1.2, support for Go on FreeBSD -requires FreeBSD 8 or above. -

    - -

    -As of Go 1.3, support for Go on FreeBSD requires that the kernel be compiled with the -COMPAT_FREEBSD32 flag configured. -

    - -

    -In concert with the switch to EABI syscalls for ARM platforms, Go 1.3 will run only on FreeBSD 10. -The x86 platforms, 386 and amd64, are unaffected. -

    - -

    Support for Native Client

    - -

    -Support for the Native Client virtual machine architecture has returned to Go with the 1.3 release. -It runs on the 32-bit Intel architectures (GOARCH=386) and also on 64-bit Intel, but using -32-bit pointers (GOARCH=amd64p32). -There is not yet support for Native Client on ARM. -Note that this is Native Client (NaCl), not Portable Native Client (PNaCl). -Details about Native Client are here; -how to set up the Go version is described here. -

    - -

    Support for NetBSD

    - -

    -As of Go 1.3, support for Go on NetBSD requires NetBSD 6.0 or above. -

    - -

    Support for OpenBSD

    - -

    -As of Go 1.3, support for Go on OpenBSD requires OpenBSD 5.5 or above. -

    - -

    Support for Plan 9

    - -

    -Go 1.3 now includes experimental support for Plan 9 on the 386 (32-bit x86) architecture. -It requires the Tsemacquire syscall, which has been in Plan 9 since June, 2012. -

    - -

    Support for Solaris

    - -

    -Go 1.3 now includes experimental support for Solaris on the amd64 (64-bit x86) architecture. -It requires illumos, Solaris 11 or above. -

    - -

    Changes to the memory model

    - -

    -The Go 1.3 memory model adds a new rule -concerning sending and receiving on buffered channels, -to make explicit that a buffered channel can be used as a simple -semaphore, using a send into the -channel to acquire and a receive from the channel to release. -This is not a language change, just a clarification about an expected property of communication. -

    - -

    Changes to the implementations and tools

    - -

    Stack

    - -

    -Go 1.3 has changed the implementation of goroutine stacks away from the old, -"segmented" model to a contiguous model. -When a goroutine needs more stack -than is available, its stack is transferred to a larger single block of memory. -The overhead of this transfer operation amortizes well and eliminates the old "hot spot" -problem when a calculation repeatedly steps across a segment boundary. -Details including performance numbers are in this -design document. -

    - -

    Changes to the garbage collector

    - -

    -For a while now, the garbage collector has been precise when examining -values in the heap; the Go 1.3 release adds equivalent precision to values on the stack. -This means that a non-pointer Go value such as an integer will never be mistaken for a -pointer and prevent unused memory from being reclaimed. -

    - -

    -Starting with Go 1.3, the runtime assumes that values with pointer type -contain pointers and other values do not. -This assumption is fundamental to the precise behavior of both stack expansion -and garbage collection. -Programs that use package unsafe -to store integers in pointer-typed values are illegal and will crash if the runtime detects the behavior. -Programs that use package unsafe to store pointers -in integer-typed values are also illegal but more difficult to diagnose during execution. -Because the pointers are hidden from the runtime, a stack expansion or garbage collection -may reclaim the memory they point at, creating -dangling pointers. -

    - -

    -Updating: Code that uses unsafe.Pointer to convert -an integer-typed value held in memory into a pointer is illegal and must be rewritten. -Such code can be identified by go vet. -

    - -

    Map iteration

    - -

    -Iterations over small maps no longer happen in a consistent order. -Go 1 defines that “The iteration order over maps -is not specified and is not guaranteed to be the same from one iteration to the next.” -To keep code from depending on map iteration order, -Go 1.0 started each map iteration at a random index in the map. -A new map implementation introduced in Go 1.1 neglected to randomize -iteration for maps with eight or fewer entries, although the iteration order -can still vary from system to system. -This has allowed people to write Go 1.1 and Go 1.2 programs that -depend on small map iteration order and therefore only work reliably on certain systems. -Go 1.3 reintroduces random iteration for small maps in order to flush out these bugs. -

    - -

    -Updating: If code assumes a fixed iteration order for small maps, -it will break and must be rewritten not to make that assumption. -Because only small maps are affected, the problem arises most often in tests. -

    - - - -

    -As part of the general overhaul to -the Go linker, the compilers and linkers have been refactored. -The linker is still a C program, but now the instruction selection phase that -was part of the linker has been moved to the compiler through the creation of a new -library called liblink. -By doing instruction selection only once, when the package is first compiled, -this can speed up compilation of large projects significantly. -

    - -

    -Updating: Although this is a major internal change, it should have no -effect on programs. -

    - -

    Status of gccgo

    - -

    -GCC release 4.9 will contain the Go 1.2 (not 1.3) version of gccgo. -The release schedules for the GCC and Go projects do not coincide, -which means that 1.3 will be available in the development branch but -that the next GCC release, 4.10, will likely have the Go 1.4 version of gccgo. -

    - -

    Changes to the go command

    - -

    -The cmd/go command has several new -features. -The go run and -go test subcommands -support a new -exec option to specify an alternate -way to run the resulting binary. -Its immediate purpose is to support NaCl. -

    - -

    -The test coverage support of the go test -subcommand now automatically sets the coverage mode to -atomic -when the race detector is enabled, to eliminate false reports about unsafe -access to coverage counters. -

    - -

    -The go test subcommand -now always builds the package, even if it has no test files. -Previously, it would do nothing if no test files were present. -

    - -

    -The go build subcommand -supports a new -i option to install dependencies -of the specified target, but not the target itself. -

    - -

    -Cross compiling with cgo enabled -is now supported. -The CC_FOR_TARGET and CXX_FOR_TARGET environment -variables are used when running all.bash to specify the cross compilers -for C and C++ code, respectively. -

    - -

    -Finally, the go command now supports packages that import Objective-C -files (suffixed .m) through cgo. -

    - -

    Changes to cgo

    - -

    -The cmd/cgo command, -which processes import "C" declarations in Go packages, -has corrected a serious bug that may cause some packages to stop compiling. -Previously, all pointers to incomplete struct types translated to the Go type *[0]byte, -with the effect that the Go compiler could not diagnose passing one kind of struct pointer -to a function expecting another. -Go 1.3 corrects this mistake by translating each different -incomplete struct to a different named type. -

    - -

    -Given the C declaration typedef struct S T for an incomplete struct S, -some Go code used this bug to refer to the types C.struct_S and C.T interchangeably. -Cgo now explicitly allows this use, even for completed struct types. -However, some Go code also used this bug to pass (for example) a *C.FILE -from one package to another. -This is not legal and no longer works: in general Go packages -should avoid exposing C types and names in their APIs. -

    - -

    -Updating: Code confusing pointers to incomplete types or -passing them across package boundaries will no longer compile -and must be rewritten. -If the conversion is correct and must be preserved, -use an explicit conversion via unsafe.Pointer. -

    - -

    SWIG 3.0 required for programs that use SWIG

    - -

    -For Go programs that use SWIG, SWIG version 3.0 is now required. -The cmd/go command will now link the -SWIG generated object files directly into the binary, rather than -building and linking with a shared library. -

    - -

    Command-line flag parsing

    - -

    -In the gc toolchain, the assemblers now use the -same command-line flag parsing rules as the Go flag package, a departure -from the traditional Unix flag parsing. -This may affect scripts that invoke the tool directly. -For example, -go tool 6a -SDfoo must now be written -go tool 6a -S -D foo. -(The same change was made to the compilers and linkers in Go 1.1.) -

    - -

    Changes to godoc

    -

    -When invoked with the -analysis flag, -godoc -now performs sophisticated static -analysis of the code it indexes. -The results of analysis are presented in both the source view and the -package documentation view, and include the call graph of each package -and the relationships between -definitions and references, -types and their methods, -interfaces and their implementations, -send and receive operations on channels, -functions and their callers, and -call sites and their callees. -

    - -

    Miscellany

    - -

    -The program misc/benchcmp that compares -performance across benchmarking runs has been rewritten. -Once a shell and awk script in the main repository, it is now a Go program in the go.tools repo. -Documentation is here. -

    - -

    -For the few of us that build Go distributions, the tool misc/dist has been -moved and renamed; it now lives in misc/makerelease, still in the main repository. -

    - -

    Performance

    - -

    -The performance of Go binaries for this release has improved in many cases due to changes -in the runtime and garbage collection, plus some changes to libraries. -Significant instances include: -

    - -
      - -
    • -The runtime handles defers more efficiently, reducing the memory footprint by about two kilobytes -per goroutine that calls defer. -
    • - -
    • -The garbage collector has been sped up, using a concurrent sweep algorithm, -better parallelization, and larger pages. -The cumulative effect can be a 50-70% reduction in collector pause time. -
    • - -
    • -The race detector (see this guide) -is now about 40% faster. -
    • - -
    • -The regular expression package regexp -is now significantly faster for certain simple expressions due to the implementation of -a second, one-pass execution engine. -The choice of which engine to use is automatic; -the details are hidden from the user. -
    • - -
    - -

    -Also, the runtime now includes in stack dumps how long a goroutine has been blocked, -which can be useful information when debugging deadlocks or performance issues. -

    - -

    Changes to the standard library

    - -

    New packages

    - -

    -A new package debug/plan9obj was added to the standard library. -It implements access to Plan 9 a.out object files. -

    - -

    Major changes to the library

    - -

    -A previous bug in crypto/tls -made it possible to skip verification in TLS inadvertently. -In Go 1.3, the bug is fixed: one must specify either ServerName or -InsecureSkipVerify, and if ServerName is specified it is enforced. -This may break existing code that incorrectly depended on insecure -behavior. -

    - -

    -There is an important new type added to the standard library: sync.Pool. -It provides an efficient mechanism for implementing certain types of caches whose memory -can be reclaimed automatically by the system. -

    - -

    -The testing package's benchmarking helper, -B, now has a -RunParallel method -to make it easier to run benchmarks that exercise multiple CPUs. -

    - -

    -Updating: The crypto/tls fix may break existing code, but such -code was erroneous and should be updated. -

    - -

    Minor changes to the library

    - -

    -The following list summarizes a number of minor changes to the library, mostly additions. -See the relevant package documentation for more information about each change. -

    - -
      - -
    • In the crypto/tls package, -a new DialWithDialer -function lets one establish a TLS connection using an existing dialer, making it easier -to control dial options such as timeouts. -The package also now reports the TLS version used by the connection in the -ConnectionState -struct. -
    • - -
    • The CreateCertificate -function of the crypto/tls package -now supports parsing (and elsewhere, serialization) of PKCS #10 certificate -signature requests. -
    • - -
    • -The formatted print functions of the fmt package now define %F -as a synonym for %f when printing floating-point values. -
    • - -
    • -The math/big package's -Int and -Rat types -now implement -encoding.TextMarshaler and -encoding.TextUnmarshaler. -
    • - -
    • -The complex power function, Pow, -now specifies the behavior when the first argument is zero. -It was undefined before. -The details are in the documentation for the function. -
    • - -
    • -The net/http package now exposes the -properties of a TLS connection used to make a client request in the new -Response.TLS field. -
    • - -
    • -The net/http package now -allows setting an optional server error logger -with Server.ErrorLog. -The default is still that all errors go to stderr. -
    • - -
    • -The net/http package now -supports disabling HTTP keep-alive connections on the server -with Server.SetKeepAlivesEnabled. -The default continues to be that the server does keep-alive (reuses -connections for multiple requests) by default. -Only resource-constrained servers or those in the process of graceful -shutdown will want to disable them. -
    • - -
    • -The net/http package adds an optional -Transport.TLSHandshakeTimeout -setting to cap the amount of time HTTP client requests will wait for -TLS handshakes to complete. -It's now also set by default -on DefaultTransport. -
    • - -
    • -The net/http package's -DefaultTransport, -used by the HTTP client code, now -enables TCP -keep-alives by default. -Other Transport -values with a nil Dial field continue to function the same -as before: no TCP keep-alives are used. -
    • - -
    • -The net/http package -now enables TCP -keep-alives for incoming server requests when -ListenAndServe -or -ListenAndServeTLS -are used. -When a server is started otherwise, TCP keep-alives are not enabled. -
    • - -
    • -The net/http package now -provides an -optional Server.ConnState -callback to hook various phases of a server connection's lifecycle -(see ConnState). -This can be used to implement rate limiting or graceful shutdown. -
    • - -
    • -The net/http package's HTTP -client now has an -optional Client.Timeout -field to specify an end-to-end timeout on requests made using the -client. -
    • - -
    • -The net/http package's -Request.ParseMultipartForm -method will now return an error if the body's Content-Type -is not multipart/form-data. -Prior to Go 1.3 it would silently fail and return nil. -Code that relies on the previous behavior should be updated. -
    • - -
    • In the net package, -the Dialer struct now -has a KeepAlive option to specify a keep-alive period for the connection. -
    • - -
    • -The net/http package's -Transport -now closes Request.Body -consistently, even on error. -
    • - -
    • -The os/exec package now implements -what the documentation has always said with regard to relative paths for the binary. -In particular, it only calls LookPath -when the binary's file name contains no path separators. -
    • - -
    • -The SetMapIndex -function in the reflect package -no longer panics when deleting from a nil map. -
    • - -
    • -If the main goroutine calls -runtime.Goexit -and all other goroutines finish execution, the program now always crashes, -reporting a detected deadlock. -Earlier versions of Go handled this situation inconsistently: most instances -were reported as deadlocks, but some trivial cases exited cleanly instead. -
    • - -
    • -The runtime/debug package now has a new function -debug.WriteHeapDump -that writes out a description of the heap. -
    • - -
    • -The CanBackquote -function in the strconv package -now considers the DEL character, U+007F, to be -non-printing. -
    • - -
    • -The syscall package now provides -SendmsgN -as an alternate version of -Sendmsg -that returns the number of bytes written. -
    • - -
    • -On Windows, the syscall package now -supports the cdecl calling convention through the addition of a new function -NewCallbackCDecl -alongside the existing function -NewCallback. -
    • - -
    • -The testing package now -diagnoses tests that call panic(nil), which are almost always erroneous. -Also, tests now write profiles (if invoked with profiling flags) even on failure. -
    • - -
    • -The unicode package and associated -support throughout the system has been upgraded from -Unicode 6.2.0 to Unicode 6.3.0. -
    • - -
    diff --git a/doc/go1.4.html b/doc/go1.4.html deleted file mode 100644 index c8f7c9c525..0000000000 --- a/doc/go1.4.html +++ /dev/null @@ -1,896 +0,0 @@ - - -

    Introduction to Go 1.4

    - -

    -The latest Go release, version 1.4, arrives as scheduled six months after 1.3. -

    - -

    -It contains only one tiny language change, -in the form of a backwards-compatible simple variant of for-range loop, -and a possibly breaking change to the compiler involving methods on pointers-to-pointers. -

    - -

    -The release focuses primarily on implementation work, improving the garbage collector -and preparing the ground for a fully concurrent collector to be rolled out in the -next few releases. -Stacks are now contiguous, reallocated when necessary rather than linking on new -"segments"; -this release therefore eliminates the notorious "hot stack split" problem. -There are some new tools available including support in the go command -for build-time source code generation. -The release also adds support for ARM processors on Android and Native Client (NaCl) -and for AMD64 on Plan 9. -

    - -

    -As always, Go 1.4 keeps the promise -of compatibility, -and almost everything -will continue to compile and run without change when moved to 1.4. -

    - -

    Changes to the language

    - -

    For-range loops

    -

    -Up until Go 1.3, for-range loop had two forms -

    - -
    -for i, v := range x {
    -	...
    -}
    -
    - -

    -and -

    - -
    -for i := range x {
    -	...
    -}
    -
    - -

    -If one was not interested in the loop values, only the iteration itself, it was still -necessary to mention a variable (probably the blank identifier, as in -for _ = range x), because -the form -

    - -
    -for range x {
    -	...
    -}
    -
    - -

    -was not syntactically permitted. -

    - -

    -This situation seemed awkward, so as of Go 1.4 the variable-free form is now legal. -The pattern arises rarely but the code can be cleaner when it does. -

    - -

    -Updating: The change is strictly backwards compatible to existing Go -programs, but tools that analyze Go parse trees may need to be modified to accept -this new form as the -Key field of RangeStmt -may now be nil. -

    - -

    Method calls on **T

    - -

    -Given these declarations, -

    - -
    -type T int
    -func (T) M() {}
    -var x **T
    -
    - -

    -both gc and gccgo accepted the method call -

    - -
    -x.M()
    -
    - -

    -which is a double dereference of the pointer-to-pointer x. -The Go specification allows a single dereference to be inserted automatically, -but not two, so this call is erroneous according to the language definition. -It has therefore been disallowed in Go 1.4, which is a breaking change, -although very few programs will be affected. -

    - -

    -Updating: Code that depends on the old, erroneous behavior will no longer -compile but is easy to fix by adding an explicit dereference. -

    - -

    Changes to the supported operating systems and architectures

    - -

    Android

    - -

    -Go 1.4 can build binaries for ARM processors running the Android operating system. -It can also build a .so library that can be loaded by an Android application -using the supporting packages in the mobile subrepository. -A brief description of the plans for this experimental port are available -here. -

    - -

    NaCl on ARM

    - -

    -The previous release introduced Native Client (NaCl) support for the 32-bit x86 -(GOARCH=386) -and 64-bit x86 using 32-bit pointers (GOARCH=amd64p32). -The 1.4 release adds NaCl support for ARM (GOARCH=arm). -

    - -

    Plan9 on AMD64

    - -

    -This release adds support for the Plan 9 operating system on AMD64 processors, -provided the kernel supports the nsec system call and uses 4K pages. -

    - -

    Changes to the compatibility guidelines

    - -

    -The unsafe package allows one -to defeat Go's type system by exploiting internal details of the implementation -or machine representation of data. -It was never explicitly specified what use of unsafe meant -with respect to compatibility as specified in the -Go compatibility guidelines. -The answer, of course, is that we can make no promise of compatibility -for code that does unsafe things. -

    - -

    -We have clarified this situation in the documentation included in the release. -The Go compatibility guidelines and the -docs for the unsafe package -are now explicit that unsafe code is not guaranteed to remain compatible. -

    - -

    -Updating: Nothing technical has changed; this is just a clarification -of the documentation. -

    - - -

    Changes to the implementations and tools

    - -

    Changes to the runtime

    - -

    -Prior to Go 1.4, the runtime (garbage collector, concurrency support, interface management, -maps, slices, strings, ...) was mostly written in C, with some assembler support. -In 1.4, much of the code has been translated to Go so that the garbage collector can scan -the stacks of programs in the runtime and get accurate information about what variables -are active. -This change was large but should have no semantic effect on programs. -

    - -

    -This rewrite allows the garbage collector in 1.4 to be fully precise, -meaning that it is aware of the location of all active pointers in the program. -This means the heap will be smaller as there will be no false positives keeping non-pointers alive. -Other related changes also reduce the heap size, which is smaller by 10%-30% overall -relative to the previous release. -

    - -

    -A consequence is that stacks are no longer segmented, eliminating the "hot split" problem. -When a stack limit is reached, a new, larger stack is allocated, all active frames for -the goroutine are copied there, and any pointers into the stack are updated. -Performance can be noticeably better in some cases and is always more predictable. -Details are available in the design document. -

    - -

    -The use of contiguous stacks means that stacks can start smaller without triggering performance issues, -so the default starting size for a goroutine's stack in 1.4 has been reduced from 8192 bytes to 2048 bytes. -

    - -

    -As preparation for the concurrent garbage collector scheduled for the 1.5 release, -writes to pointer values in the heap are now done by a function call, -called a write barrier, rather than directly from the function updating the value. -In this next release, this will permit the garbage collector to mediate writes to the heap while it is running. -This change has no semantic effect on programs in 1.4, but was -included in the release to test the compiler and the resulting performance. -

    - -

    -The implementation of interface values has been modified. -In earlier releases, the interface contained a word that was either a pointer or a one-word -scalar value, depending on the type of the concrete object stored. -This implementation was problematical for the garbage collector, -so as of 1.4 interface values always hold a pointer. -In running programs, most interface values were pointers anyway, -so the effect is minimal, but programs that store integers (for example) in -interfaces will see more allocations. -

    - -

    -As of Go 1.3, the runtime crashes if it finds a memory word that should contain -a valid pointer but instead contains an obviously invalid pointer (for example, the value 3). -Programs that store integers in pointer values may run afoul of this check and crash. -In Go 1.4, setting the GODEBUG variable -invalidptr=0 disables -the crash as a workaround, but we cannot guarantee that future releases will be -able to avoid the crash; the correct fix is to rewrite code not to alias integers and pointers. -

    - -

    Assembly

    - -

    -The language accepted by the assemblers cmd/5a, cmd/6a -and cmd/8a has had several changes, -mostly to make it easier to deliver type information to the runtime. -

    - -

    -First, the textflag.h file that defines flags for TEXT directives -has been copied from the linker source directory to a standard location so it can be -included with the simple directive -

    - -
    -#include "textflag.h"
    -
    - -

    -The more important changes are in how assembler source can define the necessary -type information. -For most programs it will suffice to move data -definitions (DATA and GLOBL directives) -out of assembly into Go files -and to write a Go declaration for each assembly function. -The assembly document describes what to do. -

    - -

    -Updating: -Assembly files that include textflag.h from its old -location will still work, but should be updated. -For the type information, most assembly routines will need no change, -but all should be examined. -Assembly source files that define data, -functions with non-empty stack frames, or functions that return pointers -need particular attention. -A description of the necessary (but simple) changes -is in the assembly document. -

    - -

    -More information about these changes is in the assembly document. -

    - -

    Status of gccgo

    - -

    -The release schedules for the GCC and Go projects do not coincide. -GCC release 4.9 contains the Go 1.2 version of gccgo. -The next release, GCC 5, will likely have the Go 1.4 version of gccgo. -

    - -

    Internal packages

    - -

    -Go's package system makes it easy to structure programs into components with clean boundaries, -but there are only two forms of access: local (unexported) and global (exported). -Sometimes one wishes to have components that are not exported, -for instance to avoid acquiring clients of interfaces to code that is part of a public repository -but not intended for use outside the program to which it belongs. -

    - -

    -The Go language does not have the power to enforce this distinction, but as of Go 1.4 the -go command introduces -a mechanism to define "internal" packages that may not be imported by packages outside -the source subtree in which they reside. -

    - -

    -To create such a package, place it in a directory named internal or in a subdirectory of a directory -named internal. -When the go command sees an import of a package with internal in its path, -it verifies that the package doing the import -is within the tree rooted at the parent of the internal directory. -For example, a package .../a/b/c/internal/d/e/f -can be imported only by code in the directory tree rooted at .../a/b/c. -It cannot be imported by code in .../a/b/g or in any other repository. -

    - -

    -For Go 1.4, the internal package mechanism is enforced for the main Go repository; -from 1.5 and onward it will be enforced for any repository. -

    - -

    -Full details of the mechanism are in -the design document. -

    - -

    Canonical import paths

    - -

    -Code often lives in repositories hosted by public services such as github.com, -meaning that the import paths for packages begin with the name of the hosting service, -github.com/rsc/pdf for example. -One can use -an existing mechanism -to provide a "custom" or "vanity" import path such as -rsc.io/pdf, but -that creates two valid import paths for the package. -That is a problem: one may inadvertently import the package through the two -distinct paths in a single program, which is wasteful; -miss an update to a package because the path being used is not recognized to be -out of date; -or break clients using the old path by moving the package to a different hosting service. -

    - -

    -Go 1.4 introduces an annotation for package clauses in Go source that identify a canonical -import path for the package. -If an import is attempted using a path that is not canonical, -the go command -will refuse to compile the importing package. -

    - -

    -The syntax is simple: put an identifying comment on the package line. -For our example, the package clause would read: -

    - -
    -package pdf // import "rsc.io/pdf"
    -
    - -

    -With this in place, -the go command will -refuse to compile a package that imports github.com/rsc/pdf, -ensuring that the code can be moved without breaking users. -

    - -

    -The check is at build time, not download time, so if go get -fails because of this check, the mis-imported package has been copied to the local machine -and should be removed manually. -

    - -

    -To complement this new feature, a check has been added at update time to verify -that the local package's remote repository matches that of its custom import. -The go get -u command will fail to -update a package if its remote repository has changed since it was first -downloaded. -The new -f flag overrides this check. -

    - -

    -Further information is in -the design document. -

    - -

    Import paths for the subrepositories

    - -

    -The Go project subrepositories (code.google.com/p/go.tools and so on) -are now available under custom import paths replacing code.google.com/p/go. with golang.org/x/, -as in golang.org/x/tools. -We will add canonical import comments to the code around June 1, 2015, -at which point Go 1.4 and later will stop accepting the old code.google.com paths. -

    - -

    -Updating: All code that imports from subrepositories should change -to use the new golang.org paths. -Go 1.0 and later can resolve and import the new paths, so updating will not break -compatibility with older releases. -Code that has not updated will stop compiling with Go 1.4 around June 1, 2015. -

    - -

    The go generate subcommand

    - -

    -The go command has a new subcommand, -go generate, -to automate the running of tools to generate source code before compilation. -For example, it can be used to run the yacc -compiler-compiler on a .y file to produce the Go source file implementing the grammar, -or to automate the generation of String methods for typed constants using the new -stringer -tool in the golang.org/x/tools subrepository. -

    - -

    -For more information, see the -design document. -

    - -

    Change to file name handling

    - -

    -Build constraints, also known as build tags, control compilation by including or excluding files -(see the documentation /go/build). -Compilation can also be controlled by the name of the file itself by "tagging" the file with -a suffix (before the .go or .s extension) with an underscore -and the name of the architecture or operating system. -For instance, the file gopher_arm.go will only be compiled if the target -processor is an ARM. -

    - -

    -Before Go 1.4, a file called just arm.go was similarly tagged, but this behavior -can break sources when new architectures are added, causing files to suddenly become tagged. -In 1.4, therefore, a file will be tagged in this manner only if the tag (architecture or operating -system name) is preceded by an underscore. -

    - -

    -Updating: Packages that depend on the old behavior will no longer compile correctly. -Files with names like windows.go or amd64.go should either -have explicit build tags added to the source or be renamed to something like -os_windows.go or support_amd64.go. -

    - -

    Other changes to the go command

    - -

    -There were a number of minor changes to the -cmd/go -command worth noting. -

    - -
      - -
    • -Unless cgo is being used to build the package, -the go command now refuses to compile C source files, -since the relevant C compilers -(6c etc.) -are intended to be removed from the installation in some future release. -(They are used today only to build part of the runtime.) -It is difficult to use them correctly in any case, so any extant uses are likely incorrect, -so we have disabled them. -
    • - -
    • -The go test -subcommand has a new flag, -o, to set the name of the resulting binary, -corresponding to the same flag in other subcommands. -The non-functional -file flag has been removed. -
    • - -
    • -The go test -subcommand will compile and link all *_test.go files in the package, -even when there are no Test functions in them. -It previously ignored such files. -
    • - -
    • -The behavior of the -go build -subcommand's --a flag has been changed for non-development installations. -For installations running a released distribution, the -a flag will no longer -rebuild the standard library and commands, to avoid overwriting the installation's files. -
    • - -
    - -

    Changes to package source layout

    - -

    -In the main Go source repository, the source code for the packages was kept in -the directory src/pkg, which made sense but differed from -other repositories, including the Go subrepositories. -In Go 1.4, the pkg level of the source tree is now gone, so for example -the fmt package's source, once kept in -directory src/pkg/fmt, now lives one level higher in src/fmt. -

    - -

    -Updating: Tools like godoc that discover source code -need to know about the new location. All tools and services maintained by the Go team -have been updated. -

    - - -

    SWIG

    - -

    -Due to runtime changes in this release, Go 1.4 requires SWIG 3.0.3. -

    - -

    Miscellany

    - -

    -The standard repository's top-level misc directory used to contain -Go support for editors and IDEs: plugins, initialization scripts and so on. -Maintaining these was becoming time-consuming -and needed external help because many of the editors listed were not used by -members of the core team. -It also required us to make decisions about which plugin was best for a given -editor, even for editors we do not use. -

    - -

    -The Go community at large is much better suited to managing this information. -In Go 1.4, therefore, this support has been removed from the repository. -Instead, there is a curated, informative list of what's available on -a wiki page. -

    - -

    Performance

    - -

    -Most programs will run about the same speed or slightly faster in 1.4 than in 1.3; -some will be slightly slower. -There are many changes, making it hard to be precise about what to expect. -

    - -

    -As mentioned above, much of the runtime was translated to Go from C, -which led to some reduction in heap sizes. -It also improved performance slightly because the Go compiler is better -at optimization, due to things like inlining, than the C compiler used to build -the runtime. -

    - -

    -The garbage collector was sped up, leading to measurable improvements for -garbage-heavy programs. -On the other hand, the new write barriers slow things down again, typically -by about the same amount but, depending on their behavior, some programs -may be somewhat slower or faster. -

    - -

    -Library changes that affect performance are documented below. -

    - -

    Changes to the standard library

    - -

    New packages

    - -

    -There are no new packages in this release. -

    - -

    Major changes to the library

    - -

    bufio.Scanner

    - -

    -The Scanner type in the -bufio package -has had a bug fixed that may require changes to custom -split functions. -The bug made it impossible to generate an empty token at EOF; the fix -changes the end conditions seen by the split function. -Previously, scanning stopped at EOF if there was no more data. -As of 1.4, the split function will be called once at EOF after input is exhausted, -so the split function can generate a final empty token -as the documentation already promised. -

    - -

    -Updating: Custom split functions may need to be modified to -handle empty tokens at EOF as desired. -

    - -

    syscall

    - -

    -The syscall package is now frozen except -for changes needed to maintain the core repository. -In particular, it will no longer be extended to support new or different system calls -that are not used by the core. -The reasons are described at length in a -separate document. -

    - -

    -A new subrepository, golang.org/x/sys, -has been created to serve as the location for new developments to support system -calls on all kernels. -It has a nicer structure, with three packages that each hold the implementation of -system calls for one of -Unix, -Windows and -Plan 9. -These packages will be curated more generously, accepting all reasonable changes -that reflect kernel interfaces in those operating systems. -See the documentation and the article mentioned above for more information. -

    - -

    -Updating: Existing programs are not affected as the syscall -package is largely unchanged from the 1.3 release. -Future development that requires system calls not in the syscall package -should build on golang.org/x/sys instead. -

    - -

    Minor changes to the library

    - -

    -The following list summarizes a number of minor changes to the library, mostly additions. -See the relevant package documentation for more information about each change. -

    - -
      - -
    • -The archive/zip package's -Writer now supports a -Flush method. -
    • - -
    • -The compress/flate, -compress/gzip, -and compress/zlib -packages now support a Reset method -for the decompressors, allowing them to reuse buffers and improve performance. -The compress/gzip package also has a -Multistream method to control support -for multistream files. -
    • - -
    • -The crypto package now has a -Signer interface, implemented by the -PrivateKey types in -crypto/ecdsa and -crypto/rsa. -
    • - -
    • -The crypto/tls package -now supports ALPN as defined in RFC 7301. -
    • - -
    • -The crypto/tls package -now supports programmatic selection of server certificates -through the new CertificateForName function -of the Config struct. -
    • - -
    • -Also in the crypto/tls package, the server now supports -TLS_FALLBACK_SCSV -to help clients detect fallback attacks. -(The Go client does not support fallback at all, so it is not vulnerable to -those attacks.) -
    • - -
    • -The database/sql package can now list all registered -Drivers. -
    • - -
    • -The debug/dwarf package now supports -UnspecifiedTypes. -
    • - -
    • -In the encoding/asn1 package, -optional elements with a default value will now only be omitted if they have that value. -
    • - -
    • -The encoding/csv package no longer -quotes empty strings but does quote the end-of-data marker \. (backslash dot). -This is permitted by the definition of CSV and allows it to work better with Postgres. -
    • - -
    • -The encoding/gob package has been rewritten to eliminate -the use of unsafe operations, allowing it to be used in environments that do not permit use of the -unsafe package. -For typical uses it will be 10-30% slower, but the delta is dependent on the type of the data and -in some cases, especially involving arrays, it can be faster. -There is no functional change. -
    • - -
    • -The encoding/xml package's -Decoder can now report its input offset. -
    • - -
    • -In the fmt package, -formatting of pointers to maps has changed to be consistent with that of pointers -to structs, arrays, and so on. -For instance, &map[string]int{"one": 1} now prints by default as -&map[one: 1] rather than as a hexadecimal pointer value. -
    • - -
    • -The image package's -Image -implementations like -RGBA and -Gray have specialized -RGBAAt and -GrayAt methods alongside the general -At method. -
    • - -
    • -The image/png package now has an -Encoder -type to control the compression level used for encoding. -
    • - -
    • -The math package now has a -Nextafter32 function. -
    • - -
    • -The net/http package's -Request type -has a new BasicAuth method -that returns the username and password from authenticated requests using the -HTTP Basic Authentication -Scheme. -
    • - -
    • The net/http package's -Transport type -has a new DialTLS hook -that allows customizing the behavior of outbound TLS connections. -
    • - -
    • -The net/http/httputil package's -ReverseProxy type -has a new field, -ErrorLog, that -provides user control of logging. -
    • - -
    • -The os package -now implements symbolic links on the Windows operating system -through the Symlink function. -Other operating systems already have this functionality. -There is also a new Unsetenv function. -
    • - -
    • -The reflect package's -Type interface -has a new method, Comparable, -that reports whether the type implements general comparisons. -
    • - -
    • -Also in the reflect package, the -Value interface is now three instead of four words -because of changes to the implementation of interfaces in the runtime. -This saves memory but has no semantic effect. -
    • - -
    • -The runtime package -now implements monotonic clocks on Windows, -as it already did for the other systems. -
    • - -
    • -The runtime package's -Mallocs counter -now counts very small allocations that were missed in Go 1.3. -This may break tests using ReadMemStats -or AllocsPerRun -due to the more accurate answer. -
    • - -
    • -In the runtime package, -an array PauseEnd -has been added to the -MemStats -and GCStats structs. -This array is a circular buffer of times when garbage collection pauses ended. -The corresponding pause durations are already recorded in -PauseNs -
    • - -
    • -The runtime/race package -now supports FreeBSD, which means the -go command's -race -flag now works on FreeBSD. -
    • - -
    • -The sync/atomic package -has a new type, Value. -Value provides an efficient mechanism for atomic loads and -stores of values of arbitrary type. -
    • - -
    • -In the syscall package's -implementation on Linux, the -Setuid -and Setgid have been disabled -because those system calls operate on the calling thread, not the whole process, which is -different from other platforms and not the expected result. -
    • - -
    • -The testing package -has a new facility to provide more control over running a set of tests. -If the test code contains a function -
      -func TestMain(m *testing.M) 
      -
      - -that function will be called instead of running the tests directly. -The M struct contains methods to access and run the tests. -
    • - -
    • -Also in the testing package, -a new Coverage -function reports the current test coverage fraction, -enabling individual tests to report how much they are contributing to the -overall coverage. -
    • - -
    • -The text/scanner package's -Scanner type -has a new function, -IsIdentRune, -allowing one to control the definition of an identifier when scanning. -
    • - -
    • -The text/template package's boolean -functions eq, lt, and so on have been generalized to allow comparison -of signed and unsigned integers, simplifying their use in practice. -(Previously one could only compare values of the same signedness.) -All negative values compare less than all unsigned values. -
    • - -
    • -The time package now uses the standard symbol for the micro prefix, -the micro symbol (U+00B5 'µ'), to print microsecond durations. -ParseDuration still accepts us -but the package no longer prints microseconds as us. -
      -Updating: Code that depends on the output format of durations -but does not use ParseDuration will need to be updated. -
    • - -
    diff --git a/doc/go1.5.html b/doc/go1.5.html deleted file mode 100644 index 2c77cf4169..0000000000 --- a/doc/go1.5.html +++ /dev/null @@ -1,1310 +0,0 @@ - - - -

    Introduction to Go 1.5

    - -

    -The latest Go release, version 1.5, -is a significant release, including major architectural changes to the implementation. -Despite that, we expect almost all Go programs to continue to compile and run as before, -because the release still maintains the Go 1 promise -of compatibility. -

    - -

    -The biggest developments in the implementation are: -

    - -
      - -
    • -The compiler and runtime are now written entirely in Go (with a little assembler). -C is no longer involved in the implementation, and so the C compiler that was -once necessary for building the distribution is gone. -
    • - -
    • -The garbage collector is now concurrent and provides dramatically lower -pause times by running, when possible, in parallel with other goroutines. -
    • - -
    • -By default, Go programs run with GOMAXPROCS set to the -number of cores available; in prior releases it defaulted to 1. -
    • - -
    • -Support for internal packages -is now provided for all repositories, not just the Go core. -
    • - -
    • -The go command now provides experimental -support for "vendoring" external dependencies. -
    • - -
    • -A new go tool trace command supports fine-grained -tracing of program execution. -
    • - -
    • -A new go doc command (distinct from godoc) -is customized for command-line use. -
    • - -
    - -

    -These and a number of other changes to the implementation and tools -are discussed below. -

    - -

    -The release also contains one small language change involving map literals. -

    - -

    -Finally, the timing of the release -strays from the usual six-month interval, -both to provide more time to prepare this major release and to shift the schedule thereafter to -time the release dates more conveniently. -

    - -

    Changes to the language

    - -

    Map literals

    - -

    -Due to an oversight, the rule that allowed the element type to be elided from slice literals was not -applied to map keys. -This has been corrected in Go 1.5. -An example will make this clear. -As of Go 1.5, this map literal, -

    - -
    -m := map[Point]string{
    -    Point{29.935523, 52.891566}:   "Persepolis",
    -    Point{-25.352594, 131.034361}: "Uluru",
    -    Point{37.422455, -122.084306}: "Googleplex",
    -}
    -
    - -

    -may be written as follows, without the Point type listed explicitly: -

    - -
    -m := map[Point]string{
    -    {29.935523, 52.891566}:   "Persepolis",
    -    {-25.352594, 131.034361}: "Uluru",
    -    {37.422455, -122.084306}: "Googleplex",
    -}
    -
    - -

    The Implementation

    - -

    No more C

    - -

    -The compiler and runtime are now implemented in Go and assembler, without C. -The only C source left in the tree is related to testing or to cgo. -There was a C compiler in the tree in 1.4 and earlier. -It was used to build the runtime; a custom compiler was necessary in part to -guarantee the C code would work with the stack management of goroutines. -Since the runtime is in Go now, there is no need for this C compiler and it is gone. -Details of the process to eliminate C are discussed elsewhere. -

    - -

    -The conversion from C was done with the help of custom tools created for the job. -Most important, the compiler was actually moved by automatic translation of -the C code into Go. -It is in effect the same program in a different language. -It is not a new implementation -of the compiler so we expect the process will not have introduced new compiler -bugs. -An overview of this process is available in the slides for -this presentation. -

    - -

    Compiler and tools

    - -

    -Independent of but encouraged by the move to Go, the names of the tools have changed. -The old names 6g, 8g and so on are gone; instead there -is just one binary, accessible as go tool compile, -that compiles Go source into binaries suitable for the architecture and operating system -specified by $GOARCH and $GOOS. -Similarly, there is now one linker (go tool link) -and one assembler (go tool asm). -The linker was translated automatically from the old C implementation, -but the assembler is a new native Go implementation discussed -in more detail below. -

    - -

    -Similar to the drop of the names 6g, 8g, and so on, -the output of the compiler and assembler are now given a plain .o suffix -rather than .8, .6, etc. -

    - - -

    Garbage collector

    - -

    -The garbage collector has been re-engineered for 1.5 as part of the development -outlined in the design document. -Expected latencies are much lower than with the collector -in prior releases, through a combination of advanced algorithms, -better scheduling of the collector, -and running more of the collection in parallel with the user program. -The "stop the world" phase of the collector -will almost always be under 10 milliseconds and usually much less. -

    - -

    -For systems that benefit from low latency, such as user-responsive web sites, -the drop in expected latency with the new collector may be important. -

    - -

    -Details of the new collector were presented in a -talk at GopherCon 2015. -

    - -

    Runtime

    - -

    -In Go 1.5, the order in which goroutines are scheduled has been changed. -The properties of the scheduler were never defined by the language, -but programs that depend on the scheduling order may be broken -by this change. -We have seen a few (erroneous) programs affected by this change. -If you have programs that implicitly depend on the scheduling -order, you will need to update them. -

    - -

    -Another potentially breaking change is that the runtime now -sets the default number of threads to run simultaneously, -defined by GOMAXPROCS, to the number -of cores available on the CPU. -In prior releases the default was 1. -Programs that do not expect to run with multiple cores may -break inadvertently. -They can be updated by removing the restriction or by setting -GOMAXPROCS explicitly. -For a more detailed discussion of this change, see -the design document. -

    - -

    Build

    - -

    -Now that the Go compiler and runtime are implemented in Go, a Go compiler -must be available to compile the distribution from source. -Thus, to build the Go core, a working Go distribution must already be in place. -(Go programmers who do not work on the core are unaffected by this change.) -Any Go 1.4 or later distribution (including gccgo) will serve. -For details, see the design document. -

    - -

    Ports

    - -

    -Due mostly to the industry's move away from the 32-bit x86 architecture, -the set of binary downloads provided is reduced in 1.5. -A distribution for the OS X operating system is provided only for the -amd64 architecture, not 386. -Similarly, the ports for Snow Leopard (Apple OS X 10.6) still work but are no -longer released as a download or maintained since Apple no longer maintains that version -of the operating system. -Also, the dragonfly/386 port is no longer supported at all -because DragonflyBSD itself no longer supports the 32-bit 386 architecture. -

    - -

    -There are however several new ports available to be built from source. -These include darwin/arm and darwin/arm64. -The new port linux/arm64 is mostly in place, but cgo -is only supported using external linking. -

    - -

    -Also available as experiments are ppc64 -and ppc64le (64-bit PowerPC, big- and little-endian). -Both these ports support cgo but -only with internal linking. -

    - -

    -On FreeBSD, Go 1.5 requires FreeBSD 8-STABLE+ because of its new use of the SYSCALL instruction. -

    - -

    -On NaCl, Go 1.5 requires SDK version pepper-41. Later pepper versions are not -compatible due to the removal of the sRPC subsystem from the NaCl runtime. -

    - -

    -On Darwin, the use of the system X.509 certificate interface can be disabled -with the ios build tag. -

    - -

    -The Solaris port now has full support for cgo and the packages -net and -crypto/x509, -as well as a number of other fixes and improvements. -

    - -

    Tools

    - -

    Translating

    - -

    -As part of the process to eliminate C from the tree, the compiler and -linker were translated from C to Go. -It was a genuine (machine assisted) translation, so the new programs are essentially -the old programs translated rather than new ones with new bugs. -We are confident the translation process has introduced few if any new bugs, -and in fact uncovered a number of previously unknown bugs, now fixed. -

    - -

    -The assembler is a new program, however; it is described below. -

    - -

    Renaming

    - -

    -The suites of programs that were the compilers (6g, 8g, etc.), -the assemblers (6a, 8a, etc.), -and the linkers (6l, 8l, etc.) -have each been consolidated into a single tool that is configured -by the environment variables GOOS and GOARCH. -The old names are gone; the new tools are available through the go tool -mechanism as go tool compile, -go tool asm, -and go tool link. -Also, the file suffixes .6, .8, etc. for the -intermediate object files are also gone; now they are just plain .o files. -

    - -

    -For example, to build and link a program on amd64 for Darwin -using the tools directly, rather than through go build, -one would run: -

    - -
    -$ export GOOS=darwin GOARCH=amd64
    -$ go tool compile program.go
    -$ go tool link program.o
    -
    - -

    Moving

    - -

    -Because the go/types package -has now moved into the main repository (see below), -the vet and -cover -tools have also been moved. -They are no longer maintained in the external golang.org/x/tools repository, -although (deprecated) source still resides there for compatibility with old releases. -

    - -

    Compiler

    - -

    -As described above, the compiler in Go 1.5 is a single Go program, -translated from the old C source, that replaces 6g, 8g, -and so on. -Its target is configured by the environment variables GOOS and GOARCH. -

    - -

    -The 1.5 compiler is mostly equivalent to the old, -but some internal details have changed. -One significant change is that evaluation of constants now uses -the math/big package -rather than a custom (and less well tested) implementation of high precision -arithmetic. -We do not expect this to affect the results. -

    - -

    -For the amd64 architecture only, the compiler has a new option, -dynlink, -that assists dynamic linking by supporting references to Go symbols -defined in external shared libraries. -

    - -

    Assembler

    - -

    -Like the compiler and linker, the assembler in Go 1.5 is a single program -that replaces the suite of assemblers (6a, -8a, etc.) and the environment variables -GOARCH and GOOS -configure the architecture and operating system. -Unlike the other programs, the assembler is a wholly new program -written in Go. -

    - -

    -The new assembler is very nearly compatible with the previous -ones, but there are a few changes that may affect some -assembler source files. -See the updated assembler guide -for more specific information about these changes. In summary: - -

    - -

    -First, the expression evaluation used for constants is a little -different. -It now uses unsigned 64-bit arithmetic and the precedence -of operators (+, -, <<, etc.) -comes from Go, not C. -We expect these changes to affect very few programs but -manual verification may be required. -

    - -

    -Perhaps more important is that on machines where -SP or PC is only an alias -for a numbered register, -such as R13 for the stack pointer and -R15 for the hardware program counter -on ARM, -a reference to such a register that does not include a symbol -is now illegal. -For example, SP and 4(SP) are -illegal but sym+4(SP) is fine. -On such machines, to refer to the hardware register use its -true R name. -

    - -

    -One minor change is that some of the old assemblers -permitted the notation -

    - -
    -constant=value
    -
    - -

    -to define a named constant. -Since this is always possible to do with the traditional -C-like #define notation, which is still -supported (the assembler includes an implementation -of a simplified C preprocessor), the feature was removed. -

    - - - -

    -The linker in Go 1.5 is now one Go program, -that replaces 6l, 8l, etc. -Its operating system and instruction set are specified -by the environment variables GOOS and GOARCH. -

    - -

    -There are several other changes. -The most significant is the addition of a -buildmode option that -expands the style of linking; it now supports -situations such as building shared libraries and allowing other languages -to call into Go libraries. -Some of these were outlined in a design document. -For a list of the available build modes and their use, run -

    - -
    -$ go help buildmode
    -
    - -

    -Another minor change is that the linker no longer records build time stamps in -the header of Windows executables. -Also, although this may be fixed, Windows cgo executables are missing some -DWARF information. -

    - -

    -Finally, the -X flag, which takes two arguments, -as in -

    - -
    --X importpath.name value
    -
    - -

    -now also accepts a more common Go flag style with a single argument -that is itself a name=value pair: -

    - -
    --X importpath.name=value
    -
    - -

    -Although the old syntax still works, it is recommended that uses of this -flag in scripts and the like be updated to the new form. -

    - -

    Go command

    - -

    -The go command's basic operation -is unchanged, but there are a number of changes worth noting. -

    - -

    -The previous release introduced the idea of a directory internal to a package -being unimportable through the go command. -In 1.4, it was tested with the introduction of some internal elements -in the core repository. -As suggested in the design document, -that change is now being made available to all repositories. -The rules are explained in the design document, but in summary any -package in or under a directory named internal may -be imported by packages rooted in the same subtree. -Existing packages with directory elements named internal may be -inadvertently broken by this change, which was why it was advertised -in the last release. -

    - -

    -Another change in how packages are handled is the experimental -addition of support for "vendoring". -For details, see the documentation for the go command -and the design document. -

    - -

    -There have also been several minor changes. -Read the documentation for full details. -

    - -
      - -
    • -SWIG support has been updated such that -.swig and .swigcxx -now require SWIG 3.0.6 or later. -
    • - -
    • -The install subcommand now removes the -binary created by the build subcommand -in the source directory, if present, -to avoid problems having two binaries present in the tree. -
    • - -
    • -The std (standard library) wildcard package name -now excludes commands. -A new cmd wildcard covers the commands. -
    • - -
    • -A new -asmflags build option -sets flags to pass to the assembler. -However, -the -ccflags build option has been dropped; -it was specific to the old, now deleted C compiler . -
    • - -
    • -A new -buildmode build option -sets the build mode, described above. -
    • - -
    • -A new -pkgdir build option -sets the location of installed package archives, -to help isolate custom builds. -
    • - -
    • -A new -toolexec build option -allows substitution of a different command to invoke -the compiler and so on. -This acts as a custom replacement for go tool. -
    • - -
    • -The test subcommand now has a -count -flag to specify how many times to run each test and benchmark. -The testing package -does the work here, through the -test.count flag. -
    • - -
    • -The generate subcommand has a couple of new features. -The -run option specifies a regular expression to select which directives -to execute; this was proposed but never implemented in 1.4. -The executing pattern now has access to two new environment variables: -$GOLINE returns the source line number of the directive -and $DOLLAR expands to a dollar sign. -
    • - -
    • -The get subcommand now has a -insecure -flag that must be enabled if fetching from an insecure repository, one that -does not encrypt the connection. -
    • - -
    - -

    Go vet command

    - -

    -The go tool vet command now does -more thorough validation of struct tags. -

    - -

    Trace command

    - -

    -A new tool is available for dynamic execution tracing of Go programs. -The usage is analogous to how the test coverage tool works. -Generation of traces is integrated into go test, -and then a separate execution of the tracing tool itself analyzes the results: -

    - -
    -$ go test -trace=trace.out path/to/package
    -$ go tool trace [flags] pkg.test trace.out
    -
    - -

    -The flags enable the output to be displayed in a browser window. -For details, run go tool trace -help. -There is also a description of the tracing facility in this -talk -from GopherCon 2015. -

    - -

    Go doc command

    - -

    -A few releases back, the go doc -command was deleted as being unnecessary. -One could always run "godoc ." instead. -The 1.5 release introduces a new go doc -command with a more convenient command-line interface than -godoc's. -It is designed for command-line usage specifically, and provides a more -compact and focused presentation of the documentation for a package -or its elements, according to the invocation. -It also provides case-insensitive matching and -support for showing the documentation for unexported symbols. -For details run "go help doc". -

    - -

    Cgo

    - -

    -When parsing #cgo lines, -the invocation ${SRCDIR} is now -expanded into the path to the source directory. -This allows options to be passed to the -compiler and linker that involve file paths relative to the -source code directory. Without the expansion the paths would be -invalid when the current working directory changes. -

    - -

    -Solaris now has full cgo support. -

    - -

    -On Windows, cgo now uses external linking by default. -

    - -

    -When a C struct ends with a zero-sized field, but the struct itself is -not zero-sized, Go code can no longer refer to the zero-sized field. -Any such references will have to be rewritten. -

    - -

    Performance

    - -

    -As always, the changes are so general and varied that precise statements -about performance are difficult to make. -The changes are even broader ranging than usual in this release, which -includes a new garbage collector and a conversion of the runtime to Go. -Some programs may run faster, some slower. -On average the programs in the Go 1 benchmark suite run a few percent faster in Go 1.5 -than they did in Go 1.4, -while as mentioned above the garbage collector's pauses are -dramatically shorter, and almost always under 10 milliseconds. -

    - -

    -Builds in Go 1.5 will be slower by a factor of about two. -The automatic translation of the compiler and linker from C to Go resulted in -unidiomatic Go code that performs poorly compared to well-written Go. -Analysis tools and refactoring helped to improve the code, but much remains to be done. -Further profiling and optimization will continue in Go 1.6 and future releases. -For more details, see these slides -and associated video. -

    - -

    Core library

    - -

    Flag

    - -

    -The flag package's -PrintDefaults -function, and method on FlagSet, -have been modified to create nicer usage messages. -The format has been changed to be more human-friendly and in the usage -messages a word quoted with `backquotes` is taken to be the name of the -flag's operand to display in the usage message. -For instance, a flag created with the invocation, -

    - -
    -cpuFlag = flag.Int("cpu", 1, "run `N` processes in parallel")
    -
    - -

    -will show the help message, -

    - -
    --cpu N
    -    	run N processes in parallel (default 1)
    -
    - -

    -Also, the default is now listed only when it is not the zero value for the type. -

    - -

    Floats in math/big

    - -

    -The math/big package -has a new, fundamental data type, -Float, -which implements arbitrary-precision floating-point numbers. -A Float value is represented by a boolean sign, -a variable-length mantissa, and a 32-bit fixed-size signed exponent. -The precision of a Float (the mantissa size in bits) -can be specified explicitly or is otherwise determined by the first -operation that creates the value. -Once created, the size of a Float's mantissa may be modified with the -SetPrec method. -Floats support the concept of infinities, such as are created by -overflow, but values that would lead to the equivalent of IEEE 754 NaNs -trigger a panic. -Float operations support all IEEE-754 rounding modes. -When the precision is set to 24 (53) bits, -operations that stay within the range of normalized float32 -(float64) -values produce the same results as the corresponding IEEE-754 -arithmetic on those values. -

    - -

    Go types

    - -

    -The go/types package -up to now has been maintained in the golang.org/x -repository; as of Go 1.5 it has been relocated to the main repository. -The code at the old location is now deprecated. -There is also a modest API change in the package, discussed below. -

    - -

    -Associated with this move, the -go/constant -package also moved to the main repository; -it was golang.org/x/tools/exact before. -The go/importer package -also moved to the main repository, -as well as some tools described above. -

    - -

    Net

    - -

    -The DNS resolver in the net package has almost always used cgo to access -the system interface. -A change in Go 1.5 means that on most Unix systems DNS resolution -will no longer require cgo, which simplifies execution -on those platforms. -Now, if the system's networking configuration permits, the native Go resolver -will suffice. -The important effect of this change is that each DNS resolution occupies a goroutine -rather than a thread, -so a program with multiple outstanding DNS requests will consume fewer operating -system resources. -

    - -

    -The decision of how to run the resolver applies at run time, not build time. -The netgo build tag that has been used to enforce the use -of the Go resolver is no longer necessary, although it still works. -A new netcgo build tag forces the use of the cgo resolver at -build time. -To force cgo resolution at run time set -GODEBUG=netdns=cgo in the environment. -More debug options are documented here. -

    - -

    -This change applies to Unix systems only. -Windows, Mac OS X, and Plan 9 systems behave as before. -

    - -

    Reflect

    - -

    -The reflect package -has two new functions: ArrayOf -and FuncOf. -These functions, analogous to the extant -SliceOf function, -create new types at runtime to describe arrays and functions. -

    - -

    Hardening

    - -

    -Several dozen bugs were found in the standard library -through randomized testing with the -go-fuzz tool. -Bugs were fixed in the -archive/tar, -archive/zip, -compress/flate, -encoding/gob, -fmt, -html/template, -image/gif, -image/jpeg, -image/png, and -text/template, -packages. -The fixes harden the implementation against incorrect and malicious inputs. -

    - -

    Minor changes to the library

    - -
      - -
    • -The archive/zip package's -Writer type now has a -SetOffset -method to specify the location within the output stream at which to write the archive. -
    • - -
    • -The Reader in the -bufio package now has a -Discard -method to discard data from the input. -
    • - -
    • -In the bytes package, -the Buffer type -now has a Cap method -that reports the number of bytes allocated within the buffer. -Similarly, in both the bytes -and strings packages, -the Reader -type now has a Size -method that reports the original length of the underlying slice or string. -
    • - -
    • -Both the bytes and -strings packages -also now have a LastIndexByte -function that locates the rightmost byte with that value in the argument. -
    • - -
    • -The crypto package -has a new interface, Decrypter, -that abstracts the behavior of a private key used in asymmetric decryption. -
    • - -
    • -In the crypto/cipher package, -the documentation for the Stream -interface has been clarified regarding the behavior when the source and destination are -different lengths. -If the destination is shorter than the source, the method will panic. -This is not a change in the implementation, only the documentation. -
    • - -
    • -Also in the crypto/cipher package, -there is now support for nonce lengths other than 96 bytes in AES's Galois/Counter mode (GCM), -which some protocols require. -
    • - -
    • -In the crypto/elliptic package, -there is now a Name field in the -CurveParams struct, -and the curves implemented in the package have been given names. -These names provide a safer way to select a curve, as opposed to -selecting its bit size, for cryptographic systems that are curve-dependent. -
    • - -
    • -Also in the crypto/elliptic package, -the Unmarshal function -now verifies that the point is actually on the curve. -(If it is not, the function returns nils). -This change guards against certain attacks. -
    • - -
    • -The crypto/sha512 -package now has support for the two truncated versions of -the SHA-512 hash algorithm, SHA-512/224 and SHA-512/256. -
    • - -
    • -The crypto/tls package -minimum protocol version now defaults to TLS 1.0. -The old default, SSLv3, is still available through Config if needed. -
    • - -
    • -The crypto/tls package -now supports Signed Certificate Timestamps (SCTs) as specified in RFC 6962. -The server serves them if they are listed in the -Certificate struct, -and the client requests them and exposes them, if present, -in its ConnectionState struct. - -
    • -The stapled OCSP response to a crypto/tls client connection, -previously only available via the -OCSPResponse method, -is now exposed in the ConnectionState struct. -
    • - -
    • -The crypto/tls server implementation -will now always call the -GetCertificate function in -the Config struct -to select a certificate for the connection when none is supplied. -
    • - -
    • -Finally, the session ticket keys in the -crypto/tls package -can now be changed while the server is running. -This is done through the new -SetSessionTicketKeys -method of the -Config type. -
    • - -
    • -In the crypto/x509 package, -wildcards are now accepted only in the leftmost label as defined in -the specification. -
    • - -
    • -Also in the crypto/x509 package, -the handling of unknown critical extensions has been changed. -They used to cause parse errors but now they are parsed and caused errors only -in Verify. -The new field UnhandledCriticalExtensions of -Certificate records these extensions. -
    • - -
    • -The DB type of the -database/sql package -now has a Stats method -to retrieve database statistics. -
    • - -
    • -The debug/dwarf -package has extensive additions to better support DWARF version 4. -See for example the definition of the new type -Class. -
    • - -
    • -The debug/dwarf package -also now supports decoding of DWARF line tables. -
    • - -
    • -The debug/elf -package now has support for the 64-bit PowerPC architecture. -
    • - -
    • -The encoding/base64 package -now supports unpadded encodings through two new encoding variables, -RawStdEncoding and -RawURLEncoding. -
    • - -
    • -The encoding/json package -now returns an UnmarshalTypeError -if a JSON value is not appropriate for the target variable or component -to which it is being unmarshaled. -
    • - -
    • -The encoding/json's -Decoder -type has a new method that provides a streaming interface for decoding -a JSON document: -Token. -It also interoperates with the existing functionality of Decode, -which will continue a decode operation already started with Decoder.Token. -
    • - -
    • -The flag package -has a new function, UnquoteUsage, -to assist in the creation of usage messages using the new convention -described above. -
    • - -
    • -In the fmt package, -a value of type Value now -prints what it holds, rather than use the reflect.Value's Stringer -method, which produces things like <int Value>. -
    • - -
    • -The EmptyStmt type -in the go/ast package now -has a boolean Implicit field that records whether the -semicolon was implicitly added or was present in the source. -
    • - -
    • -For forward compatibility the go/build package -reserves GOARCH values for a number of architectures that Go might support one day. -This is not a promise that it will. -Also, the Package struct -now has a PkgTargetRoot field that stores the -architecture-dependent root directory in which to install, if known. -
    • - -
    • -The (newly migrated) go/types -package allows one to control the prefix attached to package-level names using -the new Qualifier -function type as an argument to several functions. This is an API change for -the package, but since it is new to the core, it is not breaking the Go 1 compatibility -rules since code that uses the package must explicitly ask for it at its new location. -To update, run -go fix on your package. -
    • - -
    • -In the image package, -the Rectangle type -now implements the Image interface, -so a Rectangle can serve as a mask when drawing. -
    • - -
    • -Also in the image package, -to assist in the handling of some JPEG images, -there is now support for 4:1:1 and 4:1:0 YCbCr subsampling and basic -CMYK support, represented by the new image.CMYK struct. -
    • - -
    • -The image/color package -adds basic CMYK support, through the new -CMYK struct, -the CMYKModel color model, and the -CMYKToRGB function, as -needed by some JPEG images. -
    • - -
    • -Also in the image/color package, -the conversion of a YCbCr -value to RGBA has become more precise. -Previously, the low 8 bits were just an echo of the high 8 bits; -now they contain more accurate information. -Because of the echo property of the old code, the operation -uint8(r) to extract an 8-bit red value worked, but is incorrect. -In Go 1.5, that operation may yield a different value. -The correct code is, and always was, to select the high 8 bits: -uint8(r>>8). -Incidentally, the image/draw package -provides better support for such conversions; see -this blog post -for more information. -
    • - -
    • -Finally, as of Go 1.5 the closest match check in -Index -now honors the alpha channel. -
    • - -
    • -The image/gif package -includes a couple of generalizations. -A multiple-frame GIF file can now have an overall bounds different -from all the contained single frames' bounds. -Also, the GIF struct -now has a Disposal field -that specifies the disposal method for each frame. -
    • - -
    • -The io package -adds a CopyBuffer function -that is like Copy but -uses a caller-provided buffer, permitting control of allocation and buffer size. -
    • - -
    • -The log package -has a new LUTC flag -that causes time stamps to be printed in the UTC time zone. -It also adds a SetOutput method -for user-created loggers. -
    • - -
    • -In Go 1.4, Max was not detecting all possible NaN bit patterns. -This is fixed in Go 1.5, so programs that use math.Max on data including NaNs may behave differently, -but now correctly according to the IEEE754 definition of NaNs. -
    • - -
    • -The math/big package -adds a new Jacobi -function for integers and a new -ModSqrt -method for the Int type. -
    • - -
    • -The mime package -adds a new WordDecoder type -to decode MIME headers containing RFC 204-encoded words. -It also provides BEncoding and -QEncoding -as implementations of the encoding schemes of RFC 2045 and RFC 2047. -
    • - -
    • -The mime package also adds an -ExtensionsByType -function that returns the MIME extensions know to be associated with a given MIME type. -
    • - -
    • -There is a new mime/quotedprintable -package that implements the quoted-printable encoding defined by RFC 2045. -
    • - -
    • -The net package will now -Dial hostnames by trying each -IP address in order until one succeeds. -The Dialer.DualStack -mode now implements Happy Eyeballs -(RFC 6555) by giving the -first address family a 300ms head start; this value can be overridden by -the new Dialer.FallbackDelay. -
    • - -
    • -A number of inconsistencies in the types returned by errors in the -net package have been -tidied up. -Most now return an -OpError value -with more information than before. -Also, the OpError -type now includes a Source field that holds the local -network address. -
    • - -
    • -The net/http package now -has support for setting trailers from a server Handler. -For details, see the documentation for -ResponseWriter. -
    • - -
    • -There is a new method to cancel a net/http -Request by setting the new -Request.Cancel -field. -It is supported by http.Transport. -The Cancel field's type is compatible with the -context.Context.Done -return value. -
    • - -
    • -Also in the net/http package, -there is code to ignore the zero Time value -in the ServeContent function. -As of Go 1.5, it now also ignores a time value equal to the Unix epoch. -
    • - -
    • -The net/http/fcgi package -exports two new errors, -ErrConnClosed and -ErrRequestAborted, -to report the corresponding error conditions. -
    • - -
    • -The net/http/cgi package -had a bug that mishandled the values of the environment variables -REMOTE_ADDR and REMOTE_HOST. -This has been fixed. -Also, starting with Go 1.5 the package sets the REMOTE_PORT -variable. -
    • - -
    • -The net/mail package -adds an AddressParser -type that can parse mail addresses. -
    • - -
    • -The net/smtp package -now has a TLSConnectionState -accessor to the Client -type that returns the client's TLS state. -
    • - -
    • -The os package -has a new LookupEnv function -that is similar to Getenv -but can distinguish between an empty environment variable and a missing one. -
    • - -
    • -The os/signal package -adds new Ignore and -Reset functions. -
    • - -
    • -The runtime, -runtime/trace, -and net/http/pprof packages -each have new functions to support the tracing facilities described above: -ReadTrace, -StartTrace, -StopTrace, -Start, -Stop, and -Trace. -See the respective documentation for details. -
    • - -
    • -The runtime/pprof package -by default now includes overall memory statistics in all memory profiles. -
    • - -
    • -The strings package -has a new Compare function. -This is present to provide symmetry with the bytes package -but is otherwise unnecessary as strings support comparison natively. -
    • - -
    • -The WaitGroup implementation in -package sync -now diagnoses code that races a call to Add -against a return from Wait. -If it detects this condition, the implementation panics. -
    • - -
    • -In the syscall package, -the Linux SysProcAttr struct now has a -GidMappingsEnableSetgroups field, made necessary -by security changes in Linux 3.19. -On all Unix systems, the struct also has new Foreground and Pgid fields -to provide more control when exec'ing. -On Darwin, there is now a Syscall9 function -to support calls with too many arguments. -
    • - -
    • -The testing/quick will now -generate nil values for pointer types, -making it possible to use with recursive data structures. -Also, the package now supports generation of array types. -
    • - -
    • -In the text/template and -html/template packages, -integer constants too large to be represented as a Go integer now trigger a -parse error. Before, they were silently converted to floating point, losing -precision. -
    • - -
    • -Also in the text/template and -html/template packages, -a new Option method -allows customization of the behavior of the template during execution. -The sole implemented option allows control over how a missing key is -handled when indexing a map. -The default, which can now be overridden, is as before: to continue with an invalid value. -
    • - -
    • -The time package's -Time type has a new method -AppendFormat, -which can be used to avoid allocation when printing a time value. -
    • - -
    • -The unicode package and associated -support throughout the system has been upgraded from version 7.0 to -Unicode 8.0. -
    • - -
    diff --git a/doc/go1.6.html b/doc/go1.6.html deleted file mode 100644 index c8ec7e7991..0000000000 --- a/doc/go1.6.html +++ /dev/null @@ -1,923 +0,0 @@ - - - - - - -

    Introduction to Go 1.6

    - -

    -The latest Go release, version 1.6, arrives six months after 1.5. -Most of its changes are in the implementation of the language, runtime, and libraries. -There are no changes to the language specification. -As always, the release maintains the Go 1 promise of compatibility. -We expect almost all Go programs to continue to compile and run as before. -

    - -

    -The release adds new ports to Linux on 64-bit MIPS and Android on 32-bit x86; -defined and enforced rules for sharing Go pointers with C; -transparent, automatic support for HTTP/2; -and a new mechanism for template reuse. -

    - -

    Changes to the language

    - -

    -There are no language changes in this release. -

    - -

    Ports

    - -

    -Go 1.6 adds experimental ports to -Linux on 64-bit MIPS (linux/mips64 and linux/mips64le). -These ports support cgo but only with internal linking. -

    - -

    -Go 1.6 also adds an experimental port to Android on 32-bit x86 (android/386). -

    - -

    -On FreeBSD, Go 1.6 defaults to using clang, not gcc, as the external C compiler. -

    - -

    -On Linux on little-endian 64-bit PowerPC (linux/ppc64le), -Go 1.6 now supports cgo with external linking and -is roughly feature complete. -

    - -

    -On NaCl, Go 1.5 required SDK version pepper-41. -Go 1.6 adds support for later SDK versions. -

    - -

    -On 32-bit x86 systems using the -dynlink or -shared compilation modes, -the register CX is now overwritten by certain memory references and should -be avoided in hand-written assembly. -See the assembly documentation for details. -

    - -

    Tools

    - -

    Cgo

    - -

    -There is one major change to cgo, along with one minor change. -

    - -

    -The major change is the definition of rules for sharing Go pointers with C code, -to ensure that such C code can coexist with Go's garbage collector. -Briefly, Go and C may share memory allocated by Go -when a pointer to that memory is passed to C as part of a cgo call, -provided that the memory itself contains no pointers to Go-allocated memory, -and provided that C does not retain the pointer after the call returns. -These rules are checked by the runtime during program execution: -if the runtime detects a violation, it prints a diagnosis and crashes the program. -The checks can be disabled by setting the environment variable -GODEBUG=cgocheck=0, but note that the vast majority of -code identified by the checks is subtly incompatible with garbage collection -in one way or another. -Disabling the checks will typically only lead to more mysterious failure modes. -Fixing the code in question should be strongly preferred -over turning off the checks. -See the cgo documentation for more details. -

    - -

    -The minor change is -the addition of explicit C.complexfloat and C.complexdouble types, -separate from Go's complex64 and complex128. -Matching the other numeric types, C's complex types and Go's complex type are -no longer interchangeable. -

    - -

    Compiler Toolchain

    - -

    -The compiler toolchain is mostly unchanged. -Internally, the most significant change is that the parser is now hand-written -instead of generated from yacc. -

    - -

    -The compiler, linker, and go command have a new flag -msan, -analogous to -race and only available on linux/amd64, -that enables interoperation with the Clang MemorySanitizer. -Such interoperation is useful mainly for testing a program containing suspect C or C++ code. -

    - -

    -The linker has a new option -libgcc to set the expected location -of the C compiler support library when linking cgo code. -The option is only consulted when using -linkmode=internal, -and it may be set to none to disable the use of a support library. -

    - -

    -The implementation of build modes started in Go 1.5 has been expanded to more systems. -This release adds support for the c-shared mode on android/386, android/amd64, -android/arm64, linux/386, and linux/arm64; -for the shared mode on linux/386, linux/arm, linux/amd64, and linux/ppc64le; -and for the new pie mode (generating position-independent executables) on -android/386, android/amd64, android/arm, android/arm64, linux/386, -linux/amd64, linux/arm, linux/arm64, and linux/ppc64le. -See the design document for details. -

    - -

    -As a reminder, the linker's -X flag changed in Go 1.5. -In Go 1.4 and earlier, it took two arguments, as in -

    - -
    --X importpath.name value
    -
    - -

    -Go 1.5 added an alternative syntax using a single argument -that is itself a name=value pair: -

    - -
    --X importpath.name=value
    -
    - -

    -In Go 1.5 the old syntax was still accepted, after printing a warning -suggesting use of the new syntax instead. -Go 1.6 continues to accept the old syntax and print the warning. -Go 1.7 will remove support for the old syntax. -

    - -

    Gccgo

    - -

    -The release schedules for the GCC and Go projects do not coincide. -GCC release 5 contains the Go 1.4 version of gccgo. -The next release, GCC 6, will have the Go 1.6.1 version of gccgo. -

    - -

    Go command

    - -

    -The go command's basic operation -is unchanged, but there are a number of changes worth noting. -

    - -

    -Go 1.5 introduced experimental support for vendoring, -enabled by setting the GO15VENDOREXPERIMENT environment variable to 1. -Go 1.6 keeps the vendoring support, no longer considered experimental, -and enables it by default. -It can be disabled explicitly by setting -the GO15VENDOREXPERIMENT environment variable to 0. -Go 1.7 will remove support for the environment variable. -

    - -

    -The most likely problem caused by enabling vendoring by default happens -in source trees containing an existing directory named vendor that -does not expect to be interpreted according to new vendoring semantics. -In this case, the simplest fix is to rename the directory to anything other -than vendor and update any affected import paths. -

    - -

    -For details about vendoring, -see the documentation for the go command -and the design document. -

    - -

    -There is a new build flag, -msan, -that compiles Go with support for the LLVM memory sanitizer. -This is intended mainly for use when linking against C or C++ code -that is being checked with the memory sanitizer. -

    - -

    Go doc command

    - -

    -Go 1.5 introduced the -go doc command, -which allows references to packages using only the package name, as in -go doc http. -In the event of ambiguity, the Go 1.5 behavior was to use the package -with the lexicographically earliest import path. -In Go 1.6, ambiguity is resolved by preferring import paths with -fewer elements, breaking ties using lexicographic comparison. -An important effect of this change is that original copies of packages -are now preferred over vendored copies. -Successful searches also tend to run faster. -

    - -

    Go vet command

    - -

    -The go vet command now diagnoses -passing function or method values as arguments to Printf, -such as when passing f where f() was intended. -

    - -

    Performance

    - -

    -As always, the changes are so general and varied that precise statements -about performance are difficult to make. -Some programs may run faster, some slower. -On average the programs in the Go 1 benchmark suite run a few percent faster in Go 1.6 -than they did in Go 1.5. -The garbage collector's pauses are even lower than in Go 1.5, -especially for programs using -a large amount of memory. -

    - -

    -There have been significant optimizations bringing more than 10% improvements -to implementations of the -compress/bzip2, -compress/gzip, -crypto/aes, -crypto/elliptic, -crypto/ecdsa, and -sort packages. -

    - -

    Core library

    - -

    HTTP/2

    - -

    -Go 1.6 adds transparent support in the -net/http package -for the new HTTP/2 protocol. -Go clients and servers will automatically use HTTP/2 as appropriate when using HTTPS. -There is no exported API specific to details of the HTTP/2 protocol handling, -just as there is no exported API specific to HTTP/1.1. -

    - -

    -Programs that must disable HTTP/2 can do so by setting -Transport.TLSNextProto (for clients) -or -Server.TLSNextProto (for servers) -to a non-nil, empty map. -

    - -

    -Programs that must adjust HTTP/2 protocol-specific details can import and use -golang.org/x/net/http2, -in particular its -ConfigureServer -and -ConfigureTransport -functions. -

    - -

    Runtime

    - -

    -The runtime has added lightweight, best-effort detection of concurrent misuse of maps. -As always, if one goroutine is writing to a map, no other goroutine should be -reading or writing the map concurrently. -If the runtime detects this condition, it prints a diagnosis and crashes the program. -The best way to find out more about the problem is to run the program -under the -race detector, -which will more reliably identify the race -and give more detail. -

    - -

    -For program-ending panics, the runtime now by default -prints only the stack of the running goroutine, -not all existing goroutines. -Usually only the current goroutine is relevant to a panic, -so omitting the others significantly reduces irrelevant output -in a crash message. -To see the stacks from all goroutines in crash messages, set the environment variable -GOTRACEBACK to all -or call -debug.SetTraceback -before the crash, and rerun the program. -See the runtime documentation for details. -

    - -

    -Updating: -Uncaught panics intended to dump the state of the entire program, -such as when a timeout is detected or when explicitly handling a received signal, -should now call debug.SetTraceback("all") before panicking. -Searching for uses of -signal.Notify may help identify such code. -

    - -

    -On Windows, Go programs in Go 1.5 and earlier forced -the global Windows timer resolution to 1ms at startup -by calling timeBeginPeriod(1). -Go no longer needs this for good scheduler performance, -and changing the global timer resolution caused problems on some systems, -so the call has been removed. -

    - -

    -When using -buildmode=c-archive or --buildmode=c-shared to build an archive or a shared -library, the handling of signals has changed. -In Go 1.5 the archive or shared library would install a signal handler -for most signals. -In Go 1.6 it will only install a signal handler for the -synchronous signals needed to handle run-time panics in Go code: -SIGBUS, SIGFPE, SIGSEGV. -See the os/signal package for more -details. -

    - -

    Reflect

    - -

    -The -reflect package has -resolved a long-standing incompatibility -between the gc and gccgo toolchains -regarding embedded unexported struct types containing exported fields. -Code that walks data structures using reflection, especially to implement -serialization in the spirit -of the -encoding/json and -encoding/xml packages, -may need to be updated. -

    - -

    -The problem arises when using reflection to walk through -an embedded unexported struct-typed field -into an exported field of that struct. -In this case, reflect had incorrectly reported -the embedded field as exported, by returning an empty Field.PkgPath. -Now it correctly reports the field as unexported -but ignores that fact when evaluating access to exported fields -contained within the struct. -

    - -

    -Updating: -Typically, code that previously walked over structs and used -

    - -
    -f.PkgPath != ""
    -
    - -

    -to exclude inaccessible fields -should now use -

    - -
    -f.PkgPath != "" && !f.Anonymous
    -
    - -

    -For example, see the changes to the implementations of -encoding/json and -encoding/xml. -

    - -

    Sorting

    - -

    -In the -sort -package, -the implementation of -Sort -has been rewritten to make about 10% fewer calls to the -Interface's -Less and Swap -methods, with a corresponding overall time savings. -The new algorithm does choose a different ordering than before -for values that compare equal (those pairs for which Less(i, j) and Less(j, i) are false). -

    - -

    -Updating: -The definition of Sort makes no guarantee about the final order of equal values, -but the new behavior may still break programs that expect a specific order. -Such programs should either refine their Less implementations -to report the desired order -or should switch to -Stable, -which preserves the original input order -of equal values. -

    - -

    Templates

    - -

    -In the -text/template package, -there are two significant new features to make writing templates easier. -

    - -

    -First, it is now possible to trim spaces around template actions, -which can make template definitions more readable. -A minus sign at the beginning of an action says to trim space before the action, -and a minus sign at the end of an action says to trim space after the action. -For example, the template -

    - -
    -{{"{{"}}23 -}}
    -   <
    -{{"{{"}}- 45}}
    -
    - -

    -formats as 23<45. -

    - -

    -Second, the new {{"{{"}}block}} action, -combined with allowing redefinition of named templates, -provides a simple way to define pieces of a template that -can be replaced in different instantiations. -There is an example -in the text/template package that demonstrates this new feature. -

    - -

    Minor changes to the library

    - -
      - -
    • -The archive/tar package's -implementation corrects many bugs in rare corner cases of the file format. -One visible change is that the -Reader type's -Read method -now presents the content of special file types as being empty, -returning io.EOF immediately. -
    • - -
    • -In the archive/zip package, the -Reader type now has a -RegisterDecompressor method, -and the -Writer type now has a -RegisterCompressor method, -enabling control over compression options for individual zip files. -These take precedence over the pre-existing global -RegisterDecompressor and -RegisterCompressor functions. -
    • - -
    • -The bufio package's -Scanner type now has a -Buffer method, -to specify an initial buffer and maximum buffer size to use during scanning. -This makes it possible, when needed, to scan tokens larger than -MaxScanTokenSize. -Also for the Scanner, the package now defines the -ErrFinalToken error value, for use by -split functions to abort processing or to return a final empty token. -
    • - -
    • -The compress/flate package -has deprecated its -ReadError and -WriteError error implementations. -In Go 1.5 they were only rarely returned when an error was encountered; -now they are never returned, although they remain defined for compatibility. -
    • - -
    • -The compress/flate, -compress/gzip, and -compress/zlib packages -now report -io.ErrUnexpectedEOF for truncated input streams, instead of -io.EOF. -
    • - -
    • -The crypto/cipher package now -overwrites the destination buffer in the event of a GCM decryption failure. -This is to allow the AESNI code to avoid using a temporary buffer. -
    • - -
    • -The crypto/tls package -has a variety of minor changes. -It now allows -Listen -to succeed when the -Config -has a nil Certificates, as long as the GetCertificate callback is set, -it adds support for RSA with AES-GCM cipher suites, -and -it adds a -RecordHeaderError -to allow clients (in particular, the net/http package) -to report a better error when attempting a TLS connection to a non-TLS server. -
    • - -
    • -The crypto/x509 package -now permits certificates to contain negative serial numbers -(technically an error, but unfortunately common in practice), -and it defines a new -InsecureAlgorithmError -to give a better error message when rejecting a certificate -signed with an insecure algorithm like MD5. -
    • - -
    • -The debug/dwarf and -debug/elf packages -together add support for compressed DWARF sections. -User code needs no updating: the sections are decompressed automatically when read. -
    • - -
    • -The debug/elf package -adds support for general compressed ELF sections. -User code needs no updating: the sections are decompressed automatically when read. -However, compressed -Sections do not support random access: -they have a nil ReaderAt field. -
    • - -
    • -The encoding/asn1 package -now exports -tag and class constants -useful for advanced parsing of ASN.1 structures. -
    • - -
    • -Also in the encoding/asn1 package, -Unmarshal now rejects various non-standard integer and length encodings. -
    • - -
    • -The encoding/base64 package's -Decoder has been fixed -to process the final bytes of its input. Previously it processed as many four-byte tokens as -possible but ignored the remainder, up to three bytes. -The Decoder therefore now handles inputs in unpadded encodings (like -RawURLEncoding) correctly, -but it also rejects inputs in padded encodings that are truncated or end with invalid bytes, -such as trailing spaces. -
    • - -
    • -The encoding/json package -now checks the syntax of a -Number -before marshaling it, requiring that it conforms to the JSON specification for numeric values. -As in previous releases, the zero Number (an empty string) is marshaled as a literal 0 (zero). -
    • - -
    • -The encoding/xml package's -Marshal -function now supports a cdata attribute, such as chardata -but encoding its argument in one or more <![CDATA[ ... ]]> tags. -
    • - -
    • -Also in the encoding/xml package, -Decoder's -Token method -now reports an error when encountering EOF before seeing all open tags closed, -consistent with its general requirement that tags in the input be properly matched. -To avoid that requirement, use -RawToken. -
    • - -
    • -The fmt package now allows -any integer type as an argument to -Printf's * width and precision specification. -In previous releases, the argument to * was required to have type int. -
    • - -
    • -Also in the fmt package, -Scanf can now scan hexadecimal strings using %X, as an alias for %x. -Both formats accept any mix of upper- and lower-case hexadecimal. -
    • - -
    • -The image -and -image/color packages -add -NYCbCrA -and -NYCbCrA -types, to support Y'CbCr images with non-premultiplied alpha. -
    • - -
    • -The io package's -MultiWriter -implementation now implements a WriteString method, -for use by -WriteString. -
    • - -
    • -In the math/big package, -Int adds -Append -and -Text -methods to give more control over printing. -
    • - -
    • -Also in the math/big package, -Float now implements -encoding.TextMarshaler and -encoding.TextUnmarshaler, -allowing it to be serialized in a natural form by the -encoding/json and -encoding/xml packages. -
    • - -
    • -Also in the math/big package, -Float's -Append method now supports the special precision argument -1. -As in -strconv.ParseFloat, -precision -1 means to use the smallest number of digits necessary such that -Parse -reading the result into a Float of the same precision -will yield the original value. -
    • - -
    • -The math/rand package -adds a -Read -function, and likewise -Rand adds a -Read method. -These make it easier to generate pseudorandom test data. -Note that, like the rest of the package, -these should not be used in cryptographic settings; -for such purposes, use the crypto/rand package instead. -
    • - -
    • -The net package's -ParseMAC function now accepts 20-byte IP-over-InfiniBand (IPoIB) link-layer addresses. -
    • - - -
    • -Also in the net package, -there have been a few changes to DNS lookups. -First, the -DNSError error implementation now implements -Error, -and in particular its new -IsTemporary -method returns true for DNS server errors. -Second, DNS lookup functions such as -LookupAddr -now return rooted domain names (with a trailing dot) -on Plan 9 and Windows, to match the behavior of Go on Unix systems. -
    • - -
    • -The net/http package has -a number of minor additions beyond the HTTP/2 support already discussed. -First, the -FileServer now sorts its generated directory listings by file name. -Second, the -ServeFile function now refuses to serve a result -if the request's URL path contains “..” (dot-dot) as a path element. -Programs should typically use FileServer and -Dir -instead of calling ServeFile directly. -Programs that need to serve file content in response to requests for URLs containing dot-dot can -still call ServeContent. -Third, the -Client now allows user code to set the -Expect: 100-continue header (see -Transport.ExpectContinueTimeout). -Fourth, there are -five new error codes: -StatusPreconditionRequired (428), -StatusTooManyRequests (429), -StatusRequestHeaderFieldsTooLarge (431), and -StatusNetworkAuthenticationRequired (511) from RFC 6585, -as well as the recently-approved -StatusUnavailableForLegalReasons (451). -Fifth, the implementation and documentation of -CloseNotifier -has been substantially changed. -The Hijacker -interface now works correctly on connections that have previously -been used with CloseNotifier. -The documentation now describes when CloseNotifier -is expected to work. -
    • - -
    • -Also in the net/http package, -there are a few changes related to the handling of a -Request data structure with its Method field set to the empty string. -An empty Method field has always been documented as an alias for "GET" -and it remains so. -However, Go 1.6 fixes a few routines that did not treat an empty -Method the same as an explicit "GET". -Most notably, in previous releases -Client followed redirects only with -Method set explicitly to "GET"; -in Go 1.6 Client also follows redirects for the empty Method. -Finally, -NewRequest accepts a method argument that has not been -documented as allowed to be empty. -In past releases, passing an empty method argument resulted -in a Request with an empty Method field. -In Go 1.6, the resulting Request always has an initialized -Method field: if its argument is an empty string, NewRequest -sets the Method field in the returned Request to "GET". -
    • - -
    • -The net/http/httptest package's -ResponseRecorder now initializes a default Content-Type header -using the same content-sniffing algorithm as in -http.Server. -
    • - -
    • -The net/url package's -Parse is now stricter and more spec-compliant regarding the parsing -of host names. -For example, spaces in the host name are no longer accepted. -
    • - -
    • -Also in the net/url package, -the Error type now implements -net.Error. -
    • - -
    • -The os package's -IsExist, -IsNotExist, -and -IsPermission -now return correct results when inquiring about an -SyscallError. -
    • - -
    • -On Unix-like systems, when a write -to os.Stdout -or os.Stderr (more precisely, an os.File -opened for file descriptor 1 or 2) fails due to a broken pipe error, -the program will raise a SIGPIPE signal. -By default this will cause the program to exit; this may be changed by -calling the -os/signal -Notify function -for syscall.SIGPIPE. -A write to a broken pipe on a file descriptor other 1 or 2 will simply -return syscall.EPIPE (possibly wrapped in -os.PathError -and/or os.SyscallError) -to the caller. -The old behavior of raising an uncatchable SIGPIPE signal -after 10 consecutive writes to a broken pipe no longer occurs. -
    • - -
    • -In the os/exec package, -Cmd's -Output method continues to return an -ExitError when a command exits with an unsuccessful status. -If standard error would otherwise have been discarded, -the returned ExitError now holds a prefix and suffix -(currently 32 kB) of the failed command's standard error output, -for debugging or for inclusion in error messages. -The ExitError's -String -method does not show the captured standard error; -programs must retrieve it from the data structure -separately. -
    • - -
    • -On Windows, the path/filepath package's -Join function now correctly handles the case when the base is a relative drive path. -For example, Join(`c:`, `a`) now -returns `c:a` instead of `c:\a` as in past releases. -This may affect code that expects the incorrect result. -
    • - -
    • -In the regexp package, -the -Regexp type has always been safe for use by -concurrent goroutines. -It uses a sync.Mutex to protect -a cache of scratch spaces used during regular expression searches. -Some high-concurrency servers using the same Regexp from many goroutines -have seen degraded performance due to contention on that mutex. -To help such servers, Regexp now has a -Copy method, -which makes a copy of a Regexp that shares most of the structure -of the original but has its own scratch space cache. -Two goroutines can use different copies of a Regexp -without mutex contention. -A copy does have additional space overhead, so Copy -should only be used when contention has been observed. -
    • - -
    • -The strconv package adds -IsGraphic, -similar to IsPrint. -It also adds -QuoteToGraphic, -QuoteRuneToGraphic, -AppendQuoteToGraphic, -and -AppendQuoteRuneToGraphic, -analogous to -QuoteToASCII, -QuoteRuneToASCII, -and so on. -The ASCII family escapes all space characters except ASCII space (U+0020). -In contrast, the Graphic family does not escape any Unicode space characters (category Zs). -
    • - -
    • -In the testing package, -when a test calls -t.Parallel, -that test is paused until all non-parallel tests complete, and then -that test continues execution with all other parallel tests. -Go 1.6 changes the time reported for such a test: -previously the time counted only the parallel execution, -but now it also counts the time from the start of testing -until the call to t.Parallel. -
    • - -
    • -The text/template package -contains two minor changes, in addition to the major changes -described above. -First, it adds a new -ExecError type -returned for any error during -Execute -that does not originate in a Write to the underlying writer. -Callers can distinguish template usage errors from I/O errors by checking for -ExecError. -Second, the -Funcs method -now checks that the names used as keys in the -FuncMap -are identifiers that can appear in a template function invocation. -If not, Funcs panics. -
    • - -
    • -The time package's -Parse function has always rejected any day of month larger than 31, -such as January 32. -In Go 1.6, Parse now also rejects February 29 in non-leap years, -February 30, February 31, April 31, June 31, September 31, and November 31. -
    • - -
    - diff --git a/doc/go1.7.html b/doc/go1.7.html deleted file mode 100644 index 61076fd091..0000000000 --- a/doc/go1.7.html +++ /dev/null @@ -1,1281 +0,0 @@ - - - - - - - - -

    Introduction to Go 1.7

    - -

    -The latest Go release, version 1.7, arrives six months after 1.6. -Most of its changes are in the implementation of the toolchain, runtime, and libraries. -There is one minor change to the language specification. -As always, the release maintains the Go 1 promise of compatibility. -We expect almost all Go programs to continue to compile and run as before. -

    - -

    -The release adds a port to IBM LinuxOne; -updates the x86-64 compiler back end to generate more efficient code; -includes the context package, promoted from the -x/net subrepository -and now used in the standard library; -and adds support in the testing package for -creating hierarchies of tests and benchmarks. -The release also finalizes the vendoring support -started in Go 1.5, making it a standard feature. -

    - -

    Changes to the language

    - -

    -There is one tiny language change in this release. -The section on terminating statements -clarifies that to determine whether a statement list ends in a terminating statement, -the “final non-empty statement” is considered the end, -matching the existing behavior of the gc and gccgo compiler toolchains. -In earlier releases the definition referred only to the “final statement,” -leaving the effect of trailing empty statements at the least unclear. -The go/types -package has been updated to match the gc and gccgo compiler toolchains -in this respect. -This change has no effect on the correctness of existing programs. -

    - -

    Ports

    - -

    -Go 1.7 adds support for macOS 10.12 Sierra. -Binaries built with versions of Go before 1.7 will not work -correctly on Sierra. -

    - -

    -Go 1.7 adds an experimental port to Linux on z Systems (linux/s390x) -and the beginning of a port to Plan 9 on ARM (plan9/arm). -

    - -

    -The experimental ports to Linux on 64-bit MIPS (linux/mips64 and linux/mips64le) -added in Go 1.6 now have full support for cgo and external linking. -

    - -

    -The experimental port to Linux on little-endian 64-bit PowerPC (linux/ppc64le) -now requires the POWER8 architecture or later. -Big-endian 64-bit PowerPC (linux/ppc64) only requires the -POWER5 architecture. -

    - -

    -The OpenBSD port now requires OpenBSD 5.6 or later, for access to the getentropy(2) system call. -

    - -

    Known Issues

    - -

    -There are some instabilities on FreeBSD that are known but not understood. -These can lead to program crashes in rare cases. -See issue 16136, -issue 15658, -and issue 16396. -Any help in solving these FreeBSD-specific issues would be appreciated. -

    - -

    Tools

    - -

    Assembler

    - -

    -For 64-bit ARM systems, the vector register names have been -corrected to V0 through V31; -previous releases incorrectly referred to them as V32 through V63. -

    - -

    -For 64-bit x86 systems, the following instructions have been added: -PCMPESTRI, -RORXL, -RORXQ, -VINSERTI128, -VPADDD, -VPADDQ, -VPALIGNR, -VPBLENDD, -VPERM2F128, -VPERM2I128, -VPOR, -VPSHUFB, -VPSHUFD, -VPSLLD, -VPSLLDQ, -VPSLLQ, -VPSRLD, -VPSRLDQ, -and -VPSRLQ. -

    - -

    Compiler Toolchain

    - -

    -This release includes a new code generation back end for 64-bit x86 systems, -following a proposal from 2015 -that has been under development since then. -The new back end, based on -SSA, -generates more compact, more efficient code -and provides a better platform for optimizations -such as bounds check elimination. -The new back end reduces the CPU time required by -our benchmark programs by 5-35%. -

    - -

    -For this release, the new back end can be disabled by passing --ssa=0 to the compiler. -If you find that your program compiles or runs successfully -only with the new back end disabled, please -file a bug report. -

    - -

    -The format of exported metadata written by the compiler in package archives has changed: -the old textual format has been replaced by a more compact binary format. -This results in somewhat smaller package archives and fixes a few -long-standing corner case bugs. -

    - -

    -For this release, the new export format can be disabled by passing --newexport=0 to the compiler. -If you find that your program compiles or runs successfully -only with the new export format disabled, please -file a bug report. -

    - -

    -The linker's -X option no longer supports the unusual two-argument form --X name value, -as announced in the Go 1.6 release -and in warnings printed by the linker. -Use -X name=value instead. -

    - -

    -The compiler and linker have been optimized and run significantly faster in this release than in Go 1.6, -although they are still slower than we would like and will continue to be optimized in future releases. -

    - -

    -Due to changes across the compiler toolchain and standard library, -binaries built with this release should typically be smaller than binaries -built with Go 1.6, -sometimes by as much as 20-30%. -

    - -

    -On x86-64 systems, Go programs now maintain stack frame pointers -as expected by profiling tools like Linux's perf and Intel's VTune, -making it easier to analyze and optimize Go programs using these tools. -The frame pointer maintenance has a small run-time overhead that varies -but averages around 2%. We hope to reduce this cost in future releases. -To build a toolchain that does not use frame pointers, set -GOEXPERIMENT=noframepointer when running -make.bash, make.bat, or make.rc. -

    - -

    Cgo

    - -

    -Packages using cgo may now include -Fortran source files (in addition to C, C++, Objective C, and SWIG), -although the Go bindings must still use C language APIs. -

    - -

    -Go bindings may now use a new helper function C.CBytes. -In contrast to C.CString, which takes a Go string -and returns a *C.byte (a C char*), -C.CBytes takes a Go []byte -and returns an unsafe.Pointer (a C void*). -

    - -

    -Packages and binaries built using cgo have in past releases -produced different output on each build, -due to the embedding of temporary directory names. -When using this release with -new enough versions of GCC or Clang -(those that support the -fdebug-prefix-map option), -those builds should finally be deterministic. -

    - -

    Gccgo

    - -

    -Due to the alignment of Go's semiannual release schedule with GCC's annual release schedule, -GCC release 6 contains the Go 1.6.1 version of gccgo. -The next release, GCC 7, will likely have the Go 1.8 version of gccgo. -

    - -

    Go command

    - -

    -The go command's basic operation -is unchanged, but there are a number of changes worth noting. -

    - -

    -This release removes support for the GO15VENDOREXPERIMENT environment variable, -as announced in the Go 1.6 release. -Vendoring support -is now a standard feature of the go command and toolchain. -

    - -

    -The Package data structure made available to -“go list” now includes a -StaleReason field explaining why a particular package -is or is not considered stale (in need of rebuilding). -This field is available to the -f or -json -options and is useful for understanding why a target is being rebuilt. -

    - -

    -The “go get” command now supports -import paths referring to git.openstack.org. -

    - -

    -This release adds experimental, minimal support for building programs using -binary-only packages, -packages distributed in binary form -without the corresponding source code. -This feature is needed in some commercial settings -but is not intended to be fully integrated into the rest of the toolchain. -For example, tools that assume access to complete source code -will not work with such packages, and there are no plans to support -such packages in the “go get” command. -

    - -

    Go doc

    - -

    -The “go doc” command -now groups constructors with the type they construct, -following godoc. -

    - -

    Go vet

    - -

    -The “go vet” command -has more accurate analysis in its -copylock and -printf checks, -and a new -tests check that checks the name and signature of likely test functions. -To avoid confusion with the new -tests check, the old, unadvertised --test option has been removed; it was equivalent to -all -shadow. -

    - -

    -The vet command also has a new check, --lostcancel, which detects failure to call the -cancelation function returned by the WithCancel, -WithTimeout, and WithDeadline functions in -Go 1.7's new context package (see below). -Failure to call the function prevents the new Context -from being reclaimed until its parent is cancelled. -(The background context is never cancelled.) -

    - -

    Go tool dist

    - -

    -The new subcommand “go tool dist list” -prints all supported operating system/architecture pairs. -

    - -

    Go tool trace

    - -

    -The “go tool trace” command, -introduced in Go 1.5, -has been refined in various ways. -

    - -

    -First, collecting traces is significantly more efficient than in past releases. -In this release, the typical execution-time overhead of collecting a trace is about 25%; -in past releases it was at least 400%. -Second, trace files now include file and line number information, -making them more self-contained and making the -original executable optional when running the trace tool. -Third, the trace tool now breaks up large traces to avoid limits -in the browser-based viewer. -

    - -

    -Although the trace file format has changed in this release, -the Go 1.7 tools can still read traces from earlier releases. -

    - -

    Performance

    - -

    -As always, the changes are so general and varied that precise statements -about performance are difficult to make. -Most programs should run a bit faster, -due to speedups in the garbage collector and -optimizations in the core library. -On x86-64 systems, many programs will run significantly faster, -due to improvements in generated code brought by the -new compiler back end. -As noted above, in our own benchmarks, -the code generation changes alone typically reduce program CPU time by 5-35%. -

    - -

    - -There have been significant optimizations bringing more than 10% improvements -to implementations in the -crypto/sha1, -crypto/sha256, -encoding/binary, -fmt, -hash/adler32, -hash/crc32, -hash/crc64, -image/color, -math/big, -strconv, -strings, -unicode, -and -unicode/utf16 -packages. -

    - -

    -Garbage collection pauses should be significantly shorter than they -were in Go 1.6 for programs with large numbers of idle goroutines, -substantial stack size fluctuation, or large package-level variables. -

    - -

    Core library

    - -

    Context

    - -

    -Go 1.7 moves the golang.org/x/net/context package -into the standard library as context. -This allows the use of contexts for cancelation, timeouts, and passing -request-scoped data in other standard library packages, -including -net, -net/http, -and -os/exec, -as noted below. -

    - -

    -For more information about contexts, see the -package documentation -and the Go blog post -“Go Concurrent Patterns: Context.” -

    - -

    HTTP Tracing

    - -

    -Go 1.7 introduces net/http/httptrace, -a package that provides mechanisms for tracing events within HTTP requests. -

    - -

    Testing

    - -

    -The testing package now supports the definition -of tests with subtests and benchmarks with sub-benchmarks. -This support makes it easy to write table-driven benchmarks -and to create hierarchical tests. -It also provides a way to share common setup and tear-down code. -See the package documentation for details. -

    - -

    Runtime

    - -

    -All panics started by the runtime now use panic values -that implement both the -builtin error, -and -runtime.Error, -as -required by the language specification. -

    - -

    -During panics, if a signal's name is known, it will be printed in the stack trace. -Otherwise, the signal's number will be used, as it was before Go1.7. -

    - -

    -The new function -KeepAlive -provides an explicit mechanism for declaring -that an allocated object must be considered reachable -at a particular point in a program, -typically to delay the execution of an associated finalizer. -

    - -

    -The new function -CallersFrames -translates a PC slice obtained from -Callers -into a sequence of frames corresponding to the call stack. -This new API should be preferred instead of direct use of -FuncForPC, -because the frame sequence can more accurately describe -call stacks with inlined function calls. -

    - -

    -The new function -SetCgoTraceback -facilitates tighter integration between Go and C code executing -in the same process called using cgo. -

    - -

    -On 32-bit systems, the runtime can now use memory allocated -by the operating system anywhere in the address space, -eliminating the -“memory allocated by OS not in usable range” failure -common in some environments. -

    - -

    -The runtime can now return unused memory to the operating system on -all architectures. -In Go 1.6 and earlier, the runtime could not -release memory on ARM64, 64-bit PowerPC, or MIPS. -

    - -

    -On Windows, Go programs in Go 1.5 and earlier forced -the global Windows timer resolution to 1ms at startup -by calling timeBeginPeriod(1). -Changing the global timer resolution caused problems on some systems, -and testing suggested that the call was not needed for good scheduler performance, -so Go 1.6 removed the call. -Go 1.7 brings the call back: under some workloads the call -is still needed for good scheduler performance. -

    - - -

    Minor changes to the library

    - -

    -As always, there are various minor changes and updates to the library, -made with the Go 1 promise of compatibility -in mind. -

    - -
    bufio
    - -
    -

    -In previous releases of Go, if -Reader's -Peek method -were asked for more bytes than fit in the underlying buffer, -it would return an empty slice and the error ErrBufferFull. -Now it returns the entire underlying buffer, still accompanied by the error ErrBufferFull. -

    -
    -
    - -
    bytes
    - -
    -

    -The new functions -ContainsAny and -ContainsRune -have been added for symmetry with -the strings package. -

    - -

    -In previous releases of Go, if -Reader's -Read method -were asked for zero bytes with no data remaining, it would -return a count of 0 and no error. -Now it returns a count of 0 and the error -io.EOF. -

    - -

    -The -Reader type has a new method -Reset to allow reuse of a Reader. -

    -
    -
    - -
    compress/flate
    - -
    -

    -There are many performance optimizations throughout the package. -Decompression speed is improved by about 10%, -while compression for DefaultCompression is twice as fast. -

    - -

    -In addition to those general improvements, -the -BestSpeed -compressor has been replaced entirely and uses an -algorithm similar to Snappy, -resulting in about a 2.5X speed increase, -although the output can be 5-10% larger than with the previous algorithm. -

    - -

    -There is also a new compression level -HuffmanOnly -that applies Huffman but not Lempel-Ziv encoding. -Forgoing Lempel-Ziv encoding means that -HuffmanOnly runs about 3X faster than the new BestSpeed -but at the cost of producing compressed outputs that are 20-40% larger than those -generated by the new BestSpeed. -

    - -

    -It is important to note that both -BestSpeed and HuffmanOnly produce a compressed output that is -RFC 1951 compliant. -In other words, any valid DEFLATE decompressor will continue to be able to decompress these outputs. -

    - -

    -Lastly, there is a minor change to the decompressor's implementation of -io.Reader. In previous versions, -the decompressor deferred reporting -io.EOF until exactly no more bytes could be read. -Now, it reports -io.EOF more eagerly when reading the last set of bytes. -

    -
    -
    - -
    crypto/tls
    - -
    -

    -The TLS implementation sends the first few data packets on each connection -using small record sizes, gradually increasing to the TLS maximum record size. -This heuristic reduces the amount of data that must be received before -the first packet can be decrypted, improving communication latency over -low-bandwidth networks. -Setting -Config's -DynamicRecordSizingDisabled field to true -forces the behavior of Go 1.6 and earlier, where packets are -as large as possible from the start of the connection. -

    - -

    -The TLS client now has optional, limited support for server-initiated renegotiation, -enabled by setting the -Config's -Renegotiation field. -This is needed for connecting to many Microsoft Azure servers. -

    - -

    -The errors returned by the package now consistently begin with a -tls: prefix. -In past releases, some errors used a crypto/tls: prefix, -some used a tls: prefix, and some had no prefix at all. -

    - -

    -When generating self-signed certificates, the package no longer sets the -“Authority Key Identifier” field by default. -

    -
    -
    - -
    crypto/x509
    - -
    -

    -The new function -SystemCertPool -provides access to the entire system certificate pool if available. -There is also a new associated error type -SystemRootsError. -

    -
    -
    - -
    debug/dwarf
    - -
    -

    -The -Reader type's new -SeekPC method and the -Data type's new -Ranges method -help to find the compilation unit to pass to a -LineReader -and to identify the specific function for a given program counter. -

    -
    -
    - -
    debug/elf
    - -
    -

    -The new -R_390 relocation type -and its many predefined constants -support the S390 port. -

    -
    -
    - -
    encoding/asn1
    - -
    -

    -The ASN.1 decoder now rejects non-minimal integer encodings. -This may cause the package to reject some invalid but formerly accepted ASN.1 data. -

    -
    -
    - -
    encoding/json
    - -
    -

    -The -Encoder's new -SetIndent method -sets the indentation parameters for JSON encoding, -like in the top-level -Indent function. -

    - -

    -The -Encoder's new -SetEscapeHTML method -controls whether the -&, <, and > -characters in quoted strings should be escaped as -\u0026, \u003c, and \u003e, -respectively. -As in previous releases, the encoder defaults to applying this escaping, -to avoid certain problems that can arise when embedding JSON in HTML. -

    - -

    -In earlier versions of Go, this package only supported encoding and decoding -maps using keys with string types. -Go 1.7 adds support for maps using keys with integer types: -the encoding uses a quoted decimal representation as the JSON key. -Go 1.7 also adds support for encoding maps using non-string keys that implement -the MarshalText -(see -encoding.TextMarshaler) -method, -as well as support for decoding maps using non-string keys that implement -the UnmarshalText -(see -encoding.TextUnmarshaler) -method. -These methods are ignored for keys with string types in order to preserve -the encoding and decoding used in earlier versions of Go. -

    - -

    -When encoding a slice of typed bytes, -Marshal -now generates an array of elements encoded using -that byte type's -MarshalJSON -or -MarshalText -method if present, -only falling back to the default base64-encoded string data if neither method is available. -Earlier versions of Go accept both the original base64-encoded string encoding -and the array encoding (assuming the byte type also implements -UnmarshalJSON -or -UnmarshalText -as appropriate), -so this change should be semantically backwards compatible with earlier versions of Go, -even though it does change the chosen encoding. -

    -
    -
    - -
    go/build
    - -
    -

    -To implement the go command's new support for binary-only packages -and for Fortran code in cgo-based packages, -the -Package type -adds new fields BinaryOnly, CgoFFLAGS, and FFiles. -

    -
    -
    - -
    go/doc
    - -
    -

    -To support the corresponding change in go test described above, -Example struct adds a Unordered field -indicating whether the example may generate its output lines in any order. -

    -
    -
    - -
    io
    - -
    -

    -The package adds new constants -SeekStart, SeekCurrent, and SeekEnd, -for use with -Seeker -implementations. -These constants are preferred over os.SEEK_SET, os.SEEK_CUR, and os.SEEK_END, -but the latter will be preserved for compatibility. -

    -
    -
    - -
    math/big
    - -
    -

    -The -Float type adds -GobEncode and -GobDecode methods, -so that values of type Float can now be encoded and decoded using the -encoding/gob -package. -

    -
    -
    - -
    math/rand
    - -
    -

    -The -Read function and -Rand's -Read method -now produce a pseudo-random stream of bytes that is consistent and not -dependent on the size of the input buffer. -

    - -

    -The documentation clarifies that -Rand's Seed -and Read methods -are not safe to call concurrently, though the global -functions Seed -and Read are (and have -always been) safe. -

    -
    -
    - -
    mime/multipart
    - -
    -

    -The -Writer -implementation now emits each multipart section's header sorted by key. -Previously, iteration over a map caused the section header to use a -non-deterministic order. -

    -
    -
    - -
    net
    - -
    -

    -As part of the introduction of context, the -Dialer type has a new method -DialContext, like -Dial but adding the -context.Context -for the dial operation. -The context is intended to obsolete the Dialer's -Cancel and Deadline fields, -but the implementation continues to respect them, -for backwards compatibility. -

    - -

    -The -IP type's -String method has changed its result for invalid IP addresses. -In past releases, if an IP byte slice had length other than 0, 4, or 16, String -returned "?". -Go 1.7 adds the hexadecimal encoding of the bytes, as in "?12ab". -

    - -

    -The pure Go name resolution -implementation now respects nsswitch.conf's -stated preference for the priority of DNS lookups compared to -local file (that is, /etc/hosts) lookups. -

    -
    -
    - -
    net/http
    - -
    -

    -ResponseWriter's -documentation now makes clear that beginning to write the response -may prevent future reads on the request body. -For maximal compatibility, implementations are encouraged to -read the request body completely before writing any part of the response. -

    - -

    -As part of the introduction of context, the -Request has a new methods -Context, to retrieve the associated context, and -WithContext, to construct a copy of Request -with a modified context. -

    - -

    -In the -Server implementation, -Serve records in the request context -both the underlying *Server using the key ServerContextKey -and the local address on which the request was received (a -Addr) using the key LocalAddrContextKey. -For example, the address on which a request received is -req.Context().Value(http.LocalAddrContextKey).(net.Addr). -

    - -

    -The server's Serve method -now only enables HTTP/2 support if the Server.TLSConfig field is nil -or includes "h2" in its TLSConfig.NextProtos. -

    - -

    -The server implementation now -pads response codes less than 100 to three digits -as required by the protocol, -so that w.WriteHeader(5) uses the HTTP response -status 005, not just 5. -

    - -

    -The server implementation now correctly sends only one "Transfer-Encoding" header when "chunked" -is set explicitly, following RFC 7230. -

    - -

    -The server implementation is now stricter about rejecting requests with invalid HTTP versions. -Invalid requests claiming to be HTTP/0.x are now rejected (HTTP/0.9 was never fully supported), -and plaintext HTTP/2 requests other than the "PRI * HTTP/2.0" upgrade request are now rejected as well. -The server continues to handle encrypted HTTP/2 requests. -

    - -

    -In the server, a 200 status code is sent back by the timeout handler on an empty -response body, instead of sending back 0 as the status code. -

    - -

    -In the client, the -Transport implementation passes the request context -to any dial operation connecting to the remote server. -If a custom dialer is needed, the new Transport field -DialContext is preferred over the existing Dial field, -to allow the transport to supply a context. -

    - -

    -The -Transport also adds fields -IdleConnTimeout, -MaxIdleConns, -and -MaxResponseHeaderBytes -to help control client resources consumed -by idle or chatty servers. -

    - -

    -A -Client's configured CheckRedirect function can now -return ErrUseLastResponse to indicate that the -most recent redirect response should be returned as the -result of the HTTP request. -That response is now available to the CheckRedirect function -as req.Response. -

    - -

    -Since Go 1, the default behavior of the HTTP client is -to request server-side compression -using the Accept-Encoding request header -and then to decompress the response body transparently, -and this behavior is adjustable using the -Transport's DisableCompression field. -In Go 1.7, to aid the implementation of HTTP proxies, the -Response's new -Uncompressed field reports whether -this transparent decompression took place. -

    - -

    -DetectContentType -adds support for a few new audio and video content types. -

    -
    -
    - -
    net/http/cgi
    - -
    -

    -The -Handler -adds a new field -Stderr -that allows redirection of the child process's -standard error away from the host process's -standard error. -

    -
    -
    - -
    net/http/httptest
    - -
    -

    -The new function -NewRequest -prepares a new -http.Request -suitable for passing to an -http.Handler during a test. -

    - -

    -The -ResponseRecorder's new -Result method -returns the recorded -http.Response. -Tests that need to check the response's headers or trailers -should call Result and inspect the response fields -instead of accessing -ResponseRecorder's HeaderMap directly. -

    -
    -
    - -
    net/http/httputil
    - -
    -

    -The -ReverseProxy implementation now responds with “502 Bad Gateway” -when it cannot reach a back end; in earlier releases it responded with “500 Internal Server Error.” -

    - -

    -Both -ClientConn and -ServerConn have been documented as deprecated. -They are low-level, old, and unused by Go's current HTTP stack -and will no longer be updated. -Programs should use -http.Client, -http.Transport, -and -http.Server -instead. -

    -
    -
    - -
    net/http/pprof
    - -
    -

    -The runtime trace HTTP handler, installed to handle the path /debug/pprof/trace, -now accepts a fractional number in its seconds query parameter, -allowing collection of traces for intervals smaller than one second. -This is especially useful on busy servers. -

    -
    -
    - -
    net/mail
    - -
    -

    -The address parser now allows unescaped UTF-8 text in addresses -following RFC 6532, -but it does not apply any normalization to the result. -For compatibility with older mail parsers, -the address encoder, namely -Address's -String method, -continues to escape all UTF-8 text following RFC 5322. -

    - -

    -The ParseAddress -function and -the AddressParser.Parse -method are stricter. -They used to ignore any characters following an e-mail address, but -will now return an error for anything other than whitespace. -

    -
    -
    - -
    net/url
    - -
    -

    -The -URL's -new ForceQuery field -records whether the URL must have a query string, -in order to distinguish URLs without query strings (like /search) -from URLs with empty query strings (like /search?). -

    -
    -
    - -
    os
    - -
    -

    -IsExist now returns true for syscall.ENOTEMPTY, -on systems where that error exists. -

    - -

    -On Windows, -Remove now removes read-only files when possible, -making the implementation behave as on -non-Windows systems. -

    -
    -
    - -
    os/exec
    - -
    -

    -As part of the introduction of context, -the new constructor -CommandContext -is like -Command but includes a context that can be used to cancel the command execution. -

    -
    -
    - -
    os/user
    - -
    -

    -The -Current -function is now implemented even when cgo is not available. -

    - -

    -The new -Group type, -along with the lookup functions -LookupGroup and -LookupGroupId -and the new field GroupIds in the User struct, -provides access to system-specific user group information. -

    -
    -
    - -
    reflect
    - -
    -

    -Although -Value's -Field method has always been documented to panic -if the given field number i is out of range, it has instead -silently returned a zero -Value. -Go 1.7 changes the method to behave as documented. -

    - -

    -The new -StructOf -function constructs a struct type at run time. -It completes the set of type constructors, joining -ArrayOf, -ChanOf, -FuncOf, -MapOf, -PtrTo, -and -SliceOf. -

    - -

    -StructTag's -new method -Lookup -is like -Get -but distinguishes the tag not containing the given key -from the tag associating an empty string with the given key. -

    - -

    -The -Method and -NumMethod -methods of -Type and -Value -no longer return or count unexported methods. -

    -
    -
    - -
    strings
    - -
    -

    -In previous releases of Go, if -Reader's -Read method -were asked for zero bytes with no data remaining, it would -return a count of 0 and no error. -Now it returns a count of 0 and the error -io.EOF. -

    - -

    -The -Reader type has a new method -Reset to allow reuse of a Reader. -

    -
    -
    - -
    time
    - -
    -

    -Duration's -time.Duration.String method now reports the zero duration as "0s", not "0". -ParseDuration continues to accept both forms. -

    - -

    -The method call time.Local.String() now returns "Local" on all systems; -in earlier releases, it returned an empty string on Windows. -

    - -

    -The time zone database in -$GOROOT/lib/time has been updated -to IANA release 2016d. -This fallback database is only used when the system time zone database -cannot be found, for example on Windows. -The Windows time zone abbreviation list has also been updated. -

    -
    -
    - -
    syscall
    - -
    -

    -On Linux, the -SysProcAttr struct -(as used in -os/exec.Cmd's SysProcAttr field) -has a new Unshareflags field. -If the field is nonzero, the child process created by -ForkExec -(as used in exec.Cmd's Run method) -will call the -unshare(2) -system call before executing the new program. -

    -
    -
    - - -
    unicode
    - -
    -

    -The unicode package and associated -support throughout the system has been upgraded from version 8.0 to -Unicode 9.0. -

    -
    -
    diff --git a/doc/go1.8.html b/doc/go1.8.html deleted file mode 100644 index 2a47fac420..0000000000 --- a/doc/go1.8.html +++ /dev/null @@ -1,1666 +0,0 @@ - - - - - - -

    Introduction to Go 1.8

    - -

    -The latest Go release, version 1.8, arrives six months after Go 1.7. -Most of its changes are in the implementation of the toolchain, runtime, and libraries. -There are two minor changes to the language specification. -As always, the release maintains the Go 1 promise of compatibility. -We expect almost all Go programs to continue to compile and run as before. -

    - -

    -The release adds support for 32-bit MIPS, -updates the compiler back end to generate more efficient code, -reduces GC pauses by eliminating stop-the-world stack rescanning, -adds HTTP/2 Push support, -adds HTTP graceful shutdown, -adds more context support, -enables profiling mutexes, -and simplifies sorting slices. -

    - -

    Changes to the language

    - -

    - When explicitly converting a value from one struct type to another, - as of Go 1.8 the tags are ignored. Thus two structs that differ - only in their tags may be converted from one to the other: -

    - -
    -func example() {
    -	type T1 struct {
    -		X int `json:"foo"`
    -	}
    -	type T2 struct {
    -		X int `json:"bar"`
    -	}
    -	var v1 T1
    -	var v2 T2
    -	v1 = T1(v2) // now legal
    -}
    -
    - - -

    - The language specification now only requires that implementations - support up to 16-bit exponents in floating-point constants. This does not affect - either the “gc” or - gccgo compilers, both of - which still support 32-bit exponents. -

    - -

    Ports

    - -

    -Go now supports 32-bit MIPS on Linux for both big-endian -(linux/mips) and little-endian machines -(linux/mipsle) that implement the MIPS32r1 instruction set with FPU -or kernel FPU emulation. Note that many common MIPS-based routers lack an FPU and -have firmware that doesn't enable kernel FPU emulation; Go won't run on such machines. -

    - -

    -On DragonFly BSD, Go now requires DragonFly 4.4.4 or later. -

    - -

    -On OpenBSD, Go now requires OpenBSD 5.9 or later. -

    - -

    -The Plan 9 port's networking support is now much more complete -and matches the behavior of Unix and Windows with respect to deadlines -and cancelation. For Plan 9 kernel requirements, see the -Plan 9 wiki page. -

    - -

    - Go 1.8 now only supports OS X 10.8 or later. This is likely the last - Go release to support 10.8. Compiling Go or running - binaries on older OS X versions is untested. -

    - -

    - Go 1.8 will be the last release to support Linux on ARMv5E and ARMv6 processors: - Go 1.9 will likely require the ARMv6K (as found in the Raspberry Pi 1) or later. - To identify whether a Linux system is ARMv6K or later, run - “go tool dist -check-armv6k” - (to facilitate testing, it is also possible to just copy the dist command to the - system without installing a full copy of Go 1.8) - and if the program terminates with output "ARMv6K supported." then the system - implements ARMv6K or later. - Go on non-Linux ARM systems already requires ARMv6K or later. -

    - - -

    Known Issues

    - -

    -There are some instabilities on FreeBSD and NetBSD that are known but not understood. -These can lead to program crashes in rare cases. -See -issue 15658 and -issue 16511. -Any help in solving these issues would be appreciated. -

    - -

    Tools

    - -

    Assembler

    - -

    -For 64-bit x86 systems, the following instructions have been added: -VBROADCASTSD, -BROADCASTSS, -MOVDDUP, -MOVSHDUP, -MOVSLDUP, -VMOVDDUP, -VMOVSHDUP, and -VMOVSLDUP. -

    - -

    -For 64-bit PPC systems, the common vector scalar instructions have been -added: -LXS, -LXSDX, -LXSI, -LXSIWAX, -LXSIWZX, -LXV, -LXVD2X, -LXVDSX, -LXVW4X, -MFVSR, -MFVSRD, -MFVSRWZ, -MTVSR, -MTVSRD, -MTVSRWA, -MTVSRWZ, -STXS, -STXSDX, -STXSI, -STXSIWX, -STXV, -STXVD2X, -STXVW4X, -XSCV, -XSCVDPSP, -XSCVDPSPN, -XSCVDPSXDS, -XSCVDPSXWS, -XSCVDPUXDS, -XSCVDPUXWS, -XSCVSPDP, -XSCVSPDPN, -XSCVSXDDP, -XSCVSXDSP, -XSCVUXDDP, -XSCVUXDSP, -XSCVX, -XSCVXP, -XVCV, -XVCVDPSP, -XVCVDPSXDS, -XVCVDPSXWS, -XVCVDPUXDS, -XVCVDPUXWS, -XVCVSPDP, -XVCVSPSXDS, -XVCVSPSXWS, -XVCVSPUXDS, -XVCVSPUXWS, -XVCVSXDDP, -XVCVSXDSP, -XVCVSXWDP, -XVCVSXWSP, -XVCVUXDDP, -XVCVUXDSP, -XVCVUXWDP, -XVCVUXWSP, -XVCVX, -XVCVXP, -XXLAND, -XXLANDC, -XXLANDQ, -XXLEQV, -XXLNAND, -XXLNOR, -XXLOR, -XXLORC, -XXLORQ, -XXLXOR, -XXMRG, -XXMRGHW, -XXMRGLW, -XXPERM, -XXPERMDI, -XXSEL, -XXSI, -XXSLDWI, -XXSPLT, and -XXSPLTW. -

    - -

    Yacc

    - -

    -The yacc tool (previously available by running -“go tool yacc”) has been removed. -As of Go 1.7 it was no longer used by the Go compiler. -It has moved to the “tools” repository and is now available at -golang.org/x/tools/cmd/goyacc. -

    - -

    Fix

    - -

    - The fix tool has a new “context” - fix to change imports from “golang.org/x/net/context” - to “context”. -

    - -

    Pprof

    - -

    - The pprof tool can now profile TLS servers - and skip certificate validation by using the “https+insecure” - URL scheme. -

    - -

    - The callgrind output now has instruction-level granularity. -

    - -

    Trace

    - -

    - The trace tool has a new -pprof flag for - producing pprof-compatible blocking and latency profiles from an - execution trace. -

    - -

    - Garbage collection events are now shown more clearly in the - execution trace viewer. Garbage collection activity is shown on its - own row and GC helper goroutines are annotated with their roles. -

    - -

    Vet

    - -

    Vet is stricter in some ways and looser where it - previously caused false positives.

    - -

    Vet now checks for copying an array of locks, - duplicate JSON and XML struct field tags, - non-space-separated struct tags, - deferred calls to HTTP Response.Body.Close - before checking errors, and - indexed arguments in Printf. - It also improves existing checks.

    -

    - -

    Compiler Toolchain

    - -

    -Go 1.7 introduced a new compiler back end for 64-bit x86 systems. -In Go 1.8, that back end has been developed further and is now used for -all architectures. -

    - -

    -The new back end, based on -static single assignment form (SSA), -generates more compact, more efficient code -and provides a better platform for optimizations -such as bounds check elimination. -The new back end reduces the CPU time required by -our benchmark programs by 20-30% -on 32-bit ARM systems. For 64-bit x86 systems, which already used the SSA back end in -Go 1.7, the gains are a more modest 0-10%. Other architectures will likely -see improvements closer to the 32-bit ARM numbers. -

    - -

    - The temporary -ssa=0 compiler flag introduced in Go 1.7 - to disable the new back end has been removed in Go 1.8. -

    - -

    - In addition to enabling the new compiler back end for all systems, - Go 1.8 also introduces a new compiler front end. The new compiler - front end should not be noticeable to users but is the foundation for - future performance work. -

    - -

    - The compiler and linker have been optimized and run faster in this - release than in Go 1.7, although they are still slower than we would - like and will continue to be optimized in future releases. - Compared to the previous release, Go 1.8 is - about 15% faster. -

    - -

    Cgo

    - -

    -The Go tool now remembers the value of the CGO_ENABLED environment -variable set during make.bash and applies it to all future compilations -by default to fix issue #12808. -When doing native compilation, it is rarely necessary to explicitly set -the CGO_ENABLED environment variable as make.bash -will detect the correct setting automatically. The main reason to explicitly -set the CGO_ENABLED environment variable is when your environment -supports cgo, but you explicitly do not want cgo support, in which case, set -CGO_ENABLED=0 during make.bash or all.bash. -

    - -

    -The environment variable PKG_CONFIG may now be used to -set the program to run to handle #cgo pkg-config -directives. The default is pkg-config, the program -always used by earlier releases. This is intended to make it easier -to cross-compile -cgo code. -

    - -

    -The cgo tool now supports a -srcdir -option, which is used by the go command. -

    - -

    -If cgo code calls C.malloc, and -malloc returns NULL, the program will now -crash with an out of memory error. -C.malloc will never return nil. -Unlike most C functions, C.malloc may not be used in a -two-result form returning an errno value. -

    - -

    -If cgo is used to call a C function passing a -pointer to a C union, and if the C union can contain any pointer -values, and if cgo pointer -checking is enabled (as it is by default), the union value is now -checked for Go pointers. -

    - -

    Gccgo

    - -

    -Due to the alignment of Go's semiannual release schedule with GCC's -annual release schedule, -GCC release 6 contains the Go 1.6.1 version of gccgo. -We expect that the next release, GCC 7, will contain the Go 1.8 -version of gccgo. -

    - -

    Default GOPATH

    - -

    - The - GOPATH - environment variable now has a default value if it - is unset. It defaults to - $HOME/go on Unix and - %USERPROFILE%/go on Windows. -

    - -

    Go get

    - -

    - The “go get” command now always respects - HTTP proxy environment variables, regardless of whether - the -insecure flag is used. In previous releases, the - -insecure flag had the side effect of not using proxies. -

    - -

    Go bug

    - -

    - The new - “go bug” - command starts a bug report on GitHub, prefilled - with information about the current system. -

    - -

    Go doc

    - -

    - The - “go doc” - command now groups constants and variables with their type, - following the behavior of - godoc. -

    - -

    - In order to improve the readability of doc's - output, each summary of the first-level items is guaranteed to - occupy a single line. -

    - -

    - Documentation for a specific method in an interface definition can - now be requested, as in - “go doc net.Conn.SetDeadline”. -

    - -

    Plugins

    - -

    - Go now provides early support for plugins with a “plugin” - build mode for generating plugins written in Go, and a - new plugin package for - loading such plugins at run time. Plugin support is currently only - available on Linux. Please report any issues. -

    - -

    Runtime

    - -

    Argument Liveness

    - -

    - The garbage collector no longer considers - arguments live throughout the entirety of a function. For more - information, and for how to force a variable to remain live, see - the runtime.KeepAlive - function added in Go 1.7. -

    - -

    - Updating: - Code that sets a finalizer on an allocated object may need to add - calls to runtime.KeepAlive in functions or methods - using that object. - Read the - KeepAlive - documentation and its example for more details. -

    - -

    Concurrent Map Misuse

    - -

    -In Go 1.6, the runtime -added lightweight, -best-effort detection of concurrent misuse of maps. This release -improves that detector with support for detecting programs that -concurrently write to and iterate over a map. -

    -

    -As always, if one goroutine is writing to a map, no other goroutine should be -reading (which includes iterating) or writing the map concurrently. -If the runtime detects this condition, it prints a diagnosis and crashes the program. -The best way to find out more about the problem is to run the program -under the -race detector, -which will more reliably identify the race -and give more detail. -

    - -

    MemStats Documentation

    - -

    - The runtime.MemStats - type has been more thoroughly documented. -

    - -

    Performance

    - -

    -As always, the changes are so general and varied that precise statements -about performance are difficult to make. -Most programs should run a bit faster, -due to speedups in the garbage collector and -optimizations in the standard library. -

    - -

    -There have been optimizations to implementations in the -bytes, -crypto/aes, -crypto/cipher, -crypto/elliptic, -crypto/sha256, -crypto/sha512, -encoding/asn1, -encoding/csv, -encoding/hex, -encoding/json, -hash/crc32, -image/color, -image/draw, -math, -math/big, -reflect, -regexp, -runtime, -strconv, -strings, -syscall, -text/template, and -unicode/utf8 -packages. -

    - -

    Garbage Collector

    - -

    - Garbage collection pauses should be significantly shorter than they - were in Go 1.7, usually under 100 microseconds and often as low as - 10 microseconds. - See the - document on eliminating stop-the-world stack re-scanning - for details. More work remains for Go 1.9. -

    - -

    Defer

    - - -

    - The overhead of deferred - function calls has been reduced by about half. -

    - -

    Cgo

    - -

    The overhead of calls from Go into C has been reduced by about half.

    - -

    Standard library

    - -

    Examples

    - -

    -Examples have been added to the documentation across many packages. -

    - -

    Sort

    - -

    -The sort package -now includes a convenience function -Slice to sort a -slice given a less function. - -In many cases this means that writing a new sorter type is not -necessary. -

    - -

    -Also new are -SliceStable and -SliceIsSorted. -

    - -

    HTTP/2 Push

    - -

    -The net/http package now includes a -mechanism to -send HTTP/2 server pushes from a -Handler. -Similar to the existing Flusher and Hijacker -interfaces, an HTTP/2 -ResponseWriter -now implements the new -Pusher interface. -

    - -

    HTTP Server Graceful Shutdown

    - -

    - The HTTP Server now has support for graceful shutdown using the new - Server.Shutdown - method and abrupt shutdown using the new - Server.Close - method. -

    - -

    More Context Support

    - -

    - Continuing Go 1.7's adoption - of context.Context - into the standard library, Go 1.8 adds more context support - to existing packages: -

    - - - -

    Mutex Contention Profiling

    - -

    - The runtime and tools now support profiling contended mutexes. -

    - -

    - Most users will want to use the new -mutexprofile - flag with “go test”, - and then use pprof on the resultant file. -

    - -

    - Lower-level support is also available via the new - MutexProfile - and - SetMutexProfileFraction. -

    - -

    - A known limitation for Go 1.8 is that the profile only reports contention for - sync.Mutex, - not - sync.RWMutex. -

    - -

    Minor changes to the library

    - -

    -As always, there are various minor changes and updates to the library, -made with the Go 1 promise of compatibility -in mind. The following sections list the user visible changes and additions. -Optimizations and minor bug fixes are not listed. -

    - -
    archive/tar
    -
    - -

    - The tar implementation corrects many bugs in corner cases of the file format. - The Reader - is now able to process tar files in the PAX format with entries larger than 8GB. - The Writer - no longer produces invalid tar files in some situations involving long pathnames. -

    - -
    -
    - -
    compress/flate
    -
    - -

    - There have been some minor fixes to the encoder to improve the - compression ratio in certain situations. As a result, the exact - encoded output of DEFLATE may be different from Go 1.7. Since - DEFLATE is the underlying compression of gzip, png, zlib, and zip, - those formats may have changed outputs. -

    - -

    - The encoder, when operating in - NoCompression - mode, now produces a consistent output that is not dependent on - the size of the slices passed to the - Write - method. -

    - -

    - The decoder, upon encountering an error, now returns any - buffered data it had uncompressed along with the error. -

    - -
    -
    - - -
    compress/gzip
    -
    - -

    - The Writer - now encodes a zero MTIME field when - the Header.ModTime - field is the zero value. - - In previous releases of Go, the Writer would encode - a nonsensical value. - - Similarly, - the Reader - now reports a zero encoded MTIME field as a zero - Header.ModTime. -

    - -
    -
    - -
    context
    -
    -

    - The DeadlineExceeded - error now implements - net.Error - and reports true for both the Timeout and - Temporary methods. -

    -
    -
    - -
    crypto/tls
    -
    -

    - The new method - Conn.CloseWrite - allows TLS connections to be half closed. -

    - -

    - The new method - Config.Clone - clones a TLS configuration. -

    - -

    - - The new Config.GetConfigForClient - callback allows selecting a configuration for a client dynamically, based - on the client's - ClientHelloInfo. - - - The ClientHelloInfo - struct now has new - fields Conn, SignatureSchemes (using - the new - type SignatureScheme), - SupportedProtos, and SupportedVersions. -

    - -

    - The new Config.GetClientCertificate - callback allows selecting a client certificate based on the server's - TLS CertificateRequest message, represented by the new - CertificateRequestInfo. -

    - -

    - The new - Config.KeyLogWriter - allows debugging TLS connections - in WireShark and - similar tools. -

    - -

    - The new - Config.VerifyPeerCertificate - callback allows additional validation of a peer's presented certificate. -

    - -

    - The crypto/tls package now implements basic - countermeasures against CBC padding oracles. There should be - no explicit secret-dependent timings, but it does not attempt to - normalize memory accesses to prevent cache timing leaks. -

    - -

    - The crypto/tls package now supports - X25519 and - ChaCha20-Poly1305. - ChaCha20-Poly1305 is now prioritized unless - hardware support for AES-GCM is present. -

    - -

    - AES-128-CBC cipher suites with SHA-256 are also - now supported, but disabled by default. -

    - -
    -
    - -
    crypto/x509
    -
    -

    - PSS signatures are now supported. -

    - -

    - UnknownAuthorityError - now has a Cert field, reporting the untrusted - certificate. -

    - -

    - Certificate validation is more permissive in a few cases and - stricter in a few other cases. - -

    - -

    - Root certificates will now also be looked for - at /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem - on Linux, to support RHEL and CentOS. -

    - -
    -
    - -
    database/sql
    -
    -

    - The package now supports context.Context. There are new methods - ending in Context such as - DB.QueryContext and - DB.PrepareContext - that take context arguments. Using the new Context methods ensures that - connections are closed and returned to the connection pool when the - request is done; enables canceling in-progress queries - should the driver support that; and allows the database - pool to cancel waiting for the next available connection. -

    -

    - The IsolationLevel - can now be set when starting a transaction by setting the isolation level - on TxOptions.Isolation and passing - it to DB.BeginTx. - An error will be returned if an isolation level is selected that the driver - does not support. A read-only attribute may also be set on the transaction - by setting TxOptions.ReadOnly - to true. -

    -

    - Queries now expose the SQL column type information for drivers that support it. - Rows can return ColumnTypes - which can include SQL type information, column type lengths, and the Go type. -

    -

    - A Rows - can now represent multiple result sets. After - Rows.Next returns false, - Rows.NextResultSet - may be called to advance to the next result set. The existing Rows - should continue to be used after it advances to the next result set. -

    -

    - NamedArg may be used - as query arguments. The new function Named - helps create a NamedArg - more succinctly. -

    - If a driver supports the new - Pinger - interface, the - DB.Ping - and - DB.PingContext - methods will use that interface to check whether a - database connection is still valid. -

    -

    - The new Context query methods work for all drivers, but - Context cancelation is not responsive unless the driver has been - updated to use them. The other features require driver support in - database/sql/driver. - Driver authors should review the new interfaces. Users of existing - driver should review the driver documentation to see what - it supports and any system specific documentation on each feature. -

    -
    -
    - -
    debug/pe
    -
    -

    - The package has been extended and is now used by - the Go linker to read gcc-generated object files. - The new - File.StringTable - and - Section.Relocs - fields provide access to the COFF string table and COFF relocations. - The new - File.COFFSymbols - allows low-level access to the COFF symbol table. -

    -
    -
    - -
    encoding/base64
    -
    -

    - The new - Encoding.Strict - method returns an Encoding that causes the decoder - to return an error when the trailing padding bits are not zero. -

    -
    -
    - -
    encoding/binary
    -
    -

    - Read - and - Write - now support booleans. -

    -
    -
    - -
    encoding/json
    -
    - -

    - UnmarshalTypeError - now includes the struct and field name. -

    - -

    - A nil Marshaler - now marshals as a JSON null value. -

    - -

    - A RawMessage value now - marshals the same as its pointer type. -

    - -

    - Marshal - encodes floating-point numbers using the same format as in ES6, - preferring decimal (not exponential) notation for a wider range of values. - In particular, all floating-point integers up to 264 format the - same as the equivalent int64 representation. -

    - -

    - In previous versions of Go, unmarshaling a JSON null into an - Unmarshaler - was considered a no-op; now the Unmarshaler's - UnmarshalJSON method is called with the JSON literal - null and can define the semantics of that case. -

    - -
    -
    - -
    encoding/pem
    -
    -

    - Decode - is now strict about the format of the ending line. -

    -
    -
    - -
    encoding/xml
    -
    -

    - Unmarshal - now has wildcard support for collecting all attributes using - the new ",any,attr" struct tag. -

    -
    -
    - -
    expvar
    -
    -

    - The new methods - Int.Value, - String.Value, - Float.Value, and - Func.Value - report the current value of an exported variable. -

    - -

    - The new - function Handler - returns the package's HTTP handler, to enable installing it in - non-standard locations. -

    -
    -
    - -
    fmt
    -
    -

    - Scanf, - Fscanf, and - Sscanf now - handle spaces differently and more consistently than - previous releases. See the - scanning documentation - for details. -

    -
    -
    - -
    go/doc
    -
    -

    - The new IsPredeclared - function reports whether a string is a predeclared identifier. -

    -
    -
    - -
    go/types
    -
    -

    - The new function - Default - returns the default "typed" type for an "untyped" type. -

    - -

    - The alignment of complex64 now matches - the Go compiler. -

    -
    -
    - -
    html/template
    -
    -

    - The package now validates - the "type" attribute on - a <script> tag. -

    -
    -
    - -
    image/png
    -
    -

    - Decode - (and DecodeConfig) - now supports True Color and grayscale transparency. -

    -

    - Encoder - is now faster and creates smaller output - when encoding paletted images. -

    -
    -
    - -
    math/big
    -
    -

    - The new method - Int.Sqrt - calculates ⌊√x⌋. -

    - -

    - The new method - Float.Scan - is a support routine for - fmt.Scanner. -

    - -

    - Int.ModInverse - now supports negative numbers. -

    - -
    -
    - -
    math/rand
    -
    - -

    - The new Rand.Uint64 - method returns uint64 values. The - new Source64 - interface describes sources capable of generating such values - directly; otherwise the Rand.Uint64 method - constructs a uint64 from two calls - to Source's - Int63 method. -

    - -
    -
    - -
    mime
    -
    -

    - ParseMediaType - now preserves unnecessary backslash escapes as literals, - in order to support MSIE. - When MSIE sends a full file path (in “intranet mode”), it does not - escape backslashes: “C:\dev\go\foo.txt”, not - “C:\\dev\\go\\foo.txt”. - If we see an unnecessary backslash escape, we now assume it is from MSIE - and intended as a literal backslash. - No known MIME generators emit unnecessary backslash escapes - for simple token characters like numbers and letters. -

    -
    -
    - -
    mime/quotedprintable
    -
    - -

    - The - Reader's - parsing has been relaxed in two ways to accept - more input seen in the wild. - - - First, it accepts an equals sign (=) not followed - by two hex digits as a literal equal sign. - - - Second, it silently ignores a trailing equals sign at the end of - an encoded input. -

    - -
    -
    - -
    net
    -
    - -

    - The Conn documentation - has been updated to clarify expectations of an interface - implementation. Updates in the net/http packages - depend on implementations obeying the documentation. -

    -

    Updating: implementations of the Conn interface should verify - they implement the documented semantics. The - golang.org/x/net/nettest - package will exercise a Conn and validate it behaves properly. -

    - -

    - The new method - UnixListener.SetUnlinkOnClose - sets whether the underlying socket file should be removed from the file system when - the listener is closed. -

    - -

    - The new Buffers type permits - writing to the network more efficiently from multiple discontiguous buffers - in memory. On certain machines, for certain types of connections, - this is optimized into an OS-specific batch write operation (such as writev). -

    - -

    - The new Resolver looks up names and numbers - and supports context.Context. - The Dialer now has an optional - Resolver field. -

    - -

    - Interfaces is now supported on Solaris. -

    - -

    - The Go DNS resolver now supports resolv.conf's “rotate” - and “option ndots:0” options. The “ndots” option is - now respected in the same way as libresolve. -

    - -
    -
    - -
    net/http
    -
    - -

    Server changes:

    -
      -
    • The server now supports graceful shutdown support, mentioned above.
    • - -
    • - The Server - adds configuration options - ReadHeaderTimeout and IdleTimeout - and documents WriteTimeout. -
    • - -
    • - FileServer - and - ServeContent - now support HTTP If-Match conditional requests, - in addition to the previous If-None-Match - support for ETags properly formatted according to RFC 7232, section 2.3. -
    • -
    - -

    - There are several additions to what a server's Handler can do: -

    - -
      -
    • - The Context - returned - by Request.Context - is canceled if the underlying net.Conn - closes. For instance, if the user closes their browser in the - middle of a slow request, the Handler can now - detect that the user is gone. This complements the - existing CloseNotifier - support. This functionality requires that the underlying - net.Conn implements - recently clarified interface documentation. -
    • - -
    • - To serve trailers produced after the header has already been written, - see the new - TrailerPrefix - mechanism. -
    • - -
    • - A Handler can now abort a response by panicking - with the error - ErrAbortHandler. -
    • - -
    • - A Write of zero bytes to a - ResponseWriter - is now defined as a - way to test whether a ResponseWriter has been hijacked: - if so, the Write returns - ErrHijacked - without printing an error - to the server's error log. -
    • - -
    - -

    Client & Transport changes:

    -
      -
    • - The Client - now copies most request headers on redirect. See - the documentation - on the Client type for details. -
    • - -
    • - The Transport - now supports international domain names. Consequently, so do - Get and other helpers. -
    • - -
    • - The Client now supports 301, 307, and 308 redirects. - - For example, Client.Post now follows 301 - redirects, converting them to GET requests - without bodies, like it did for 302 and 303 redirect responses - previously. - - The Client now also follows 307 and 308 - redirects, preserving the original request method and body, if - any. If the redirect requires resending the request body, the - request must have the new - Request.GetBody - field defined. - NewRequest - sets Request.GetBody automatically for common - body types. -
    • - -
    • - The Transport now rejects requests for URLs with - ports containing non-digit characters. -
    • - -
    • - The Transport will now retry non-idempotent - requests if no bytes were written before a network failure - and the request has no body. -
    • - -
    • - The - new Transport.ProxyConnectHeader - allows configuration of header values to send to a proxy - during a CONNECT request. -
    • - -
    • - The DefaultTransport.Dialer - now enables DualStack ("Happy Eyeballs") support, - allowing the use of IPv4 as a backup if it looks like IPv6 might be - failing. -
    • - -
    • - The Transport - no longer reads a byte of a non-nil - Request.Body - when the - Request.ContentLength - is zero to determine whether the ContentLength - is actually zero or just undefined. - To explicitly signal that a body has zero length, - either set it to nil, or set it to the new value - NoBody. - The new NoBody value is intended for use by Request - constructor functions; it is used by - NewRequest. -
    • -
    - -
    -
    - -
    net/http/httptrace
    -
    -

    - There is now support for tracing a client request's TLS handshakes with - the new - ClientTrace.TLSHandshakeStart - and - ClientTrace.TLSHandshakeDone. -

    -
    -
    - -
    net/http/httputil
    -
    -

    - The ReverseProxy - has a new optional hook, - ModifyResponse, - for modifying the response from the back end before proxying it to the client. -

    - -
    -
    - -
    net/mail
    -
    - -

    - Empty quoted strings are once again allowed in the name part of - an address. That is, Go 1.4 and earlier accepted - "" <gopher@example.com>, - but Go 1.5 introduced a bug that rejected this address. - The address is recognized again. -

    - -

    - The - Header.Date - method has always provided a way to parse - the Date: header. - A new function - ParseDate - allows parsing dates found in other - header lines, such as the Resent-Date: header. -

    - -
    -
    - -
    net/smtp
    -
    - -

    - If an implementation of the - Auth.Start - method returns an empty toServer value, - the package no longer sends - trailing whitespace in the SMTP AUTH command, - which some servers rejected. -

    - -
    -
    - -
    net/url
    -
    - -

    - The new functions - PathEscape - and - PathUnescape - are similar to the query escaping and unescaping functions but - for path elements. -

    - -

    - The new methods - URL.Hostname - and - URL.Port - return the hostname and port fields of a URL, - correctly handling the case where the port may not be present. -

    - -

    - The existing method - URL.ResolveReference - now properly handles paths with escaped bytes without losing - the escaping. -

    - -

    - The URL type now implements - encoding.BinaryMarshaler and - encoding.BinaryUnmarshaler, - making it possible to process URLs in gob data. -

    - -

    - Following RFC 3986, - Parse - now rejects URLs like this_that:other/thing instead of - interpreting them as relative paths (this_that is not a valid scheme). - To force interpretation as a relative path, - such URLs should be prefixed with “./”. - The URL.String method now inserts this prefix as needed. -

    - -
    -
    - -
    os
    -
    -

    - The new function - Executable returns - the path name of the running executable. -

    - -

    - An attempt to call a method on - an os.File that has - already been closed will now return the new error - value os.ErrClosed. - Previously it returned a system-specific error such - as syscall.EBADF. -

    - -

    - On Unix systems, os.Rename - will now return an error when used to rename a directory to an - existing empty directory. - Previously it would fail when renaming to a non-empty directory - but succeed when renaming to an empty directory. - This makes the behavior on Unix correspond to that of other systems. -

    - -

    - On Windows, long absolute paths are now transparently converted to - extended-length paths (paths that start with “\\?\”). - This permits the package to work with files whose path names are - longer than 260 characters. -

    - -

    - On Windows, os.IsExist - will now return true for the system - error ERROR_DIR_NOT_EMPTY. - This roughly corresponds to the existing handling of the Unix - error ENOTEMPTY. -

    - -

    - On Plan 9, files that are not served by #M will now - have ModeDevice set in - the value returned - by FileInfo.Mode. -

    -
    -
    - -
    path/filepath
    -
    -

    - A number of bugs and corner cases on Windows were fixed: - Abs now calls Clean as documented, - Glob now matches - “\\?\c:\*”, - EvalSymlinks now - correctly handles “C:.”, and - Clean now properly - handles a leading “..” in the path. -

    -
    -
    - -
    reflect
    -
    -

    - The new function - Swapper was - added to support sort.Slice. -

    -
    -
    - -
    strconv
    -
    -

    - The Unquote - function now strips carriage returns (\r) in - backquoted raw strings, following the - Go language semantics. -

    -
    -
    - -
    syscall
    -
    -

    - The Getpagesize - now returns the system's size, rather than a constant value. - Previously it always returned 4KB. -

    - -

    - The signature - of Utimes has - changed on Solaris to match all the other Unix systems' - signature. Portable code should continue to use - os.Chtimes instead. -

    - -

    - The X__cmsg_data field has been removed from - Cmsghdr. -

    -
    -
    - -
    text/template
    -
    -

    - Template.Execute - can now take a - reflect.Value as its data - argument, and - FuncMap - functions can also accept and return reflect.Value. -

    - -
    -
    - -
    time
    -
    - -

    The new function - Until complements - the analogous Since function. -

    - -

    - ParseDuration - now accepts long fractional parts. -

    - -

    - Parse - now rejects dates before the start of a month, such as June 0; - it already rejected dates beyond the end of the month, such as - June 31 and July 32. -

    - -

    - The tzdata database has been updated to version - 2016j for systems that don't already have a local time zone - database. -

    - -

    -

    -
    - -
    testing
    -
    -

    - The new method - T.Name - (and B.Name) returns the name of the current - test or benchmark. -

    - -

    - The new function - CoverMode - reports the test coverage mode. -

    - -

    - Tests and benchmarks are now marked as failed if the race - detector is enabled and a data race occurs during execution. - Previously, individual test cases would appear to pass, - and only the overall execution of the test binary would fail. -

    - -

    - The signature of the - MainStart - function has changed, as allowed by the documentation. It is an - internal detail and not part of the Go 1 compatibility promise. - If you're not calling MainStart directly but see - errors, that likely means you set the - normally-empty GOROOT environment variable and it - doesn't match the version of your go command's binary. -

    - -
    -
    - -
    unicode
    -
    -

    - SimpleFold - now returns its argument unchanged if the provided input was an invalid rune. - Previously, the implementation failed with an index bounds check panic. -

    -
    -
    diff --git a/doc/go1.9.html b/doc/go1.9.html deleted file mode 100644 index 86ee257d03..0000000000 --- a/doc/go1.9.html +++ /dev/null @@ -1,1024 +0,0 @@ - - - - - - -

    Introduction to Go 1.9

    - -

    - The latest Go release, version 1.9, arrives six months - after Go 1.8 and is the tenth release in - the Go 1.x - series. - There are two changes to the language: - adding support for type aliases and defining when implementations - may fuse floating point operations. - Most of the changes are in the implementation of the toolchain, - runtime, and libraries. - As always, the release maintains the Go 1 - promise of compatibility. - We expect almost all Go programs to continue to compile and run as - before. -

    - -

    - The release - adds transparent monotonic time support, - parallelizes compilation of functions within a package, - better supports test helper functions, - includes a new bit manipulation package, - and has a new concurrent map type. -

    - -

    Changes to the language

    - -

    - There are two changes to the language. -

    -

    - Go now supports type aliases to support gradual code repair while - moving a type between packages. - The type alias - design document - and an - article on refactoring cover the problem in detail. - In short, a type alias declaration has the form: -

    - -
    -type T1 = T2
    -
    - -

    - This declaration introduces an alias name T1—an - alternate spelling—for the type denoted by T2; that is, - both T1 and T2 denote the same type. -

    - -

    - A smaller language change is that the - language specification - now states when implementations are allowed to fuse floating - point operations together, such as by using an architecture's "fused - multiply and add" (FMA) instruction to compute x*y + z - without rounding the intermediate result x*y. - To force the intermediate rounding, write float64(x*y) + z. -

    - -

    Ports

    - -

    - There are no new supported operating systems or processor - architectures in this release. -

    - -

    ppc64x requires POWER8

    - -

    - Both GOARCH=ppc64 and GOARCH=ppc64le now - require at least POWER8 support. In previous releases, - only GOARCH=ppc64le required POWER8 and the big - endian ppc64 architecture supported older - hardware. -

    - -

    FreeBSD

    - -

    - Go 1.9 is the last release that will run on FreeBSD 9.3, - which is already - unsupported by FreeBSD. - Go 1.10 will require FreeBSD 10.3+. -

    - -

    OpenBSD 6.0

    - -

    - Go 1.9 now enables PT_TLS generation for cgo binaries and thus - requires OpenBSD 6.0 or newer. Go 1.9 no longer supports - OpenBSD 5.9. -

    - -

    Known Issues

    - -

    - There are some instabilities on FreeBSD that are known but not understood. - These can lead to program crashes in rare cases. - See issue 15658. - Any help in solving this FreeBSD-specific issue would be appreciated. -

    - -

    - Go stopped running NetBSD builders during the Go 1.9 development - cycle due to NetBSD kernel crashes, up to and including NetBSD 7.1. - As Go 1.9 is being released, NetBSD 7.1.1 is being released with a fix. - However, at this time we have no NetBSD builders passing our test suite. - Any help investigating the - various NetBSD issues - would be appreciated. -

    - -

    Tools

    - -

    Parallel Compilation

    - -

    - The Go compiler now supports compiling a package's functions in parallel, taking - advantage of multiple cores. This is in addition to the go command's - existing support for parallel compilation of separate packages. - Parallel compilation is on by default, but it can be disabled by setting the - environment variable GO19CONCURRENTCOMPILATION to 0. -

    - -

    Vendor matching with ./...

    - -

    - By popular request, ./... no longer matches packages - in vendor directories in tools accepting package names, - such as go test. To match vendor - directories, write ./vendor/.... -

    - -

    Moved GOROOT

    - -

    - The go tool will now use the path from which it - was invoked to attempt to locate the root of the Go install tree. - This means that if the entire Go installation is moved to a new - location, the go tool should continue to work as usual. - This may be overridden by setting GOROOT in the environment, - which should only be done in unusual circumstances. - Note that this does not affect the result of - the runtime.GOROOT function, which - will continue to report the original installation location; - this may be fixed in later releases. -

    - -

    Compiler Toolchain

    - -

    - Complex division is now C99-compatible. This has always been the - case in gccgo and is now fixed in the gc toolchain. -

    - -

    - The linker will now generate DWARF information for cgo executables on Windows. -

    - -

    - The compiler now includes lexical scopes in the generated DWARF if the - -N -l flags are provided, allowing - debuggers to hide variables that are not in scope. The .debug_info - section is now DWARF version 4. -

    - -

    - The values of GOARM and GO386 now affect a - compiled package's build ID, as used by the go tool's - dependency caching. -

    - -

    Assembler

    - -

    - The four-operand ARM MULA instruction is now assembled correctly, - with the addend register as the third argument and the result - register as the fourth and final argument. - In previous releases, the two meanings were reversed. - The three-operand form, in which the fourth argument is implicitly - the same as the third, is unaffected. - Code using four-operand MULA instructions - will need to be updated, but we believe this form is very rarely used. - MULAWT and MULAWB were already - using the correct order in all forms and are unchanged. -

    - -

    - The assembler now supports ADDSUBPS/PD, completing the - two missing x86 SSE3 instructions. -

    - -

    Doc

    - -

    - Long lists of arguments are now truncated. This improves the readability - of go doc on some generated code. -

    - -

    - Viewing documentation on struct fields is now supported. - For example, go doc http.Client.Jar. -

    - -

    Env

    - -

    - The new go env -json flag - enables JSON output, instead of the default OS-specific output - format. -

    - -

    Test

    - -

    - The go test - command accepts a new -list flag, which takes a regular - expression as an argument and prints to stdout the name of any - tests, benchmarks, or examples that match it, without running them. -

    - - -

    Pprof

    - -

    - Profiles produced by the runtime/pprof package now - include symbol information, so they can be viewed - in go tool pprof - without the binary that produced the profile. -

    - -

    - The go tool pprof command now - uses the HTTP proxy information defined in the environment, using - http.ProxyFromEnvironment. -

    - -

    Vet

    - - -

    - The vet command - has been better integrated into the - go tool, - so go vet now supports all standard build - flags while vet's own flags are now available - from go vet as well as - from go tool vet. -

    - -

    Gccgo

    - -

    -Due to the alignment of Go's semiannual release schedule with GCC's -annual release schedule, -GCC release 7 contains the Go 1.8.3 version of gccgo. -We expect that the next release, GCC 8, will contain the Go 1.10 -version of gccgo. -

    - -

    Runtime

    - -

    Call stacks with inlined frames

    - -

    - Users of - runtime.Callers - should avoid directly inspecting the resulting PC slice and instead use - runtime.CallersFrames - to get a complete view of the call stack, or - runtime.Caller - to get information about a single caller. - This is because an individual element of the PC slice cannot account - for inlined frames or other nuances of the call stack. -

    - -

    - Specifically, code that directly iterates over the PC slice and uses - functions such as - runtime.FuncForPC - to resolve each PC individually will miss inlined frames. - To get a complete view of the stack, such code should instead use - CallersFrames. - Likewise, code should not assume that the length returned by - Callers is any indication of the call depth. - It should instead count the number of frames returned by - CallersFrames. -

    - -

    - Code that queries a single caller at a specific depth should use - Caller rather than passing a slice of length 1 to - Callers. -

    - -

    - runtime.CallersFrames - has been available since Go 1.7, so code can be updated prior to - upgrading to Go 1.9. -

    - -

    Performance

    - -

    - As always, the changes are so general and varied that precise - statements about performance are difficult to make. Most programs - should run a bit faster, due to speedups in the garbage collector, - better generated code, and optimizations in the core library. -

    - -

    Garbage Collector

    - -

    - Library functions that used to trigger stop-the-world garbage - collection now trigger concurrent garbage collection. - - Specifically, runtime.GC, - debug.SetGCPercent, - and - debug.FreeOSMemory, - now trigger concurrent garbage collection, blocking only the calling - goroutine until the garbage collection is done. -

    - -

    - The - debug.SetGCPercent - function only triggers a garbage collection if one is immediately - necessary because of the new GOGC value. - This makes it possible to adjust GOGC on-the-fly. -

    - -

    - Large object allocation performance is significantly improved in - applications using large (>50GB) heaps containing many large - objects. -

    - -

    - The runtime.ReadMemStats - function now takes less than 100µs even for very large heaps. -

    - -

    Core library

    - -

    Transparent Monotonic Time support

    - -

    - The time package now transparently - tracks monotonic time in each Time - value, making computing durations between two Time values - a safe operation in the presence of wall clock adjustments. - See the package docs and - design document - for details. -

    - -

    New bit manipulation package

    - -

    - Go 1.9 includes a new package, - math/bits, with optimized - implementations for manipulating bits. On most architectures, - functions in this package are additionally recognized by the - compiler and treated as intrinsics for additional performance. -

    - -

    Test Helper Functions

    - -

    - The - new (*T).Helper - and (*B).Helper - methods mark the calling function as a test helper function. When - printing file and line information, that function will be skipped. - This permits writing test helper functions while still having useful - line numbers for users. -

    - -

    Concurrent Map

    - -

    - The new Map type - in the sync package - is a concurrent map with amortized-constant-time loads, stores, and - deletes. It is safe for multiple goroutines to call a Map's methods - concurrently. -

    - -

    Profiler Labels

    - -

    - The runtime/pprof package - now supports adding labels to pprof profiler records. - Labels form a key-value map that is used to distinguish calls of the - same function in different contexts when looking at profiles - with the pprof command. - The pprof package's - new Do function - runs code associated with some provided labels. Other new functions - in the package help work with labels. -

    - -
- - -

Minor changes to the library

- -

- As always, there are various minor changes and updates to the library, - made with the Go 1 promise of compatibility - in mind. -

- -
archive/zip
-
-

- The - ZIP Writer - now sets the UTF-8 bit in - the FileHeader.Flags - when appropriate. -

- -
- -
crypto/rand
-
-

- On Linux, Go now calls the getrandom system call - without the GRND_NONBLOCK flag; it will now block - until the kernel has sufficient randomness. On kernels predating - the getrandom system call, Go continues to read - from /dev/urandom. -

- -
- -
crypto/x509
-
-

- - On Unix systems the environment - variables SSL_CERT_FILE - and SSL_CERT_DIR can now be used to override the - system default locations for the SSL certificate file and SSL - certificate files directory, respectively. -

- -

The FreeBSD file /usr/local/etc/ssl/cert.pem is - now included in the certificate search path. -

- -

- - The package now supports excluded domains in name constraints. - In addition to enforcing such constraints, - CreateCertificate - will create certificates with excluded name constraints - if the provided template certificate has the new - field - ExcludedDNSDomains - populated. -

- -

- - If any SAN extension, including with no DNS names, is present - in the certificate, then the Common Name from - Subject is ignored. - In previous releases, the code tested only whether DNS-name SANs were - present in a certificate. -

- -
- -
database/sql
-
-

- The package will now use a cached Stmt if - available in Tx.Stmt. - This prevents statements from being re-prepared each time - Tx.Stmt is called. -

- -

- The package now allows drivers to implement their own argument checkers by implementing - driver.NamedValueChecker. - This also allows drivers to support OUTPUT and INOUT parameter types. - Out should be used to return output parameters - when supported by the driver. -

- -

- Rows.Scan can now scan user-defined string types. - Previously the package supported scanning into numeric types like type Int int64. It now also supports - scanning into string types like type String string. -

- -

- The new DB.Conn method returns the new - Conn type representing an - exclusive connection to the database from the connection pool. All queries run on - a Conn will use the same underlying - connection until Conn.Close is called - to return the connection to the connection pool. -

- -
- -
encoding/asn1
-
-

- The new - NullBytes - and - NullRawValue - represent the ASN.1 NULL type. -

- -
- -
encoding/base32
-
-

- The new Encoding.WithPadding - method adds support for custom padding characters and disabling padding. -

- -
- -
encoding/csv
-
-

- The new field - Reader.ReuseRecord - controls whether calls to - Read - may return a slice sharing the backing array of the previous - call's returned slice for improved performance. -

- -
- -
fmt
-
-

- The sharp flag ('#') is now supported when printing - floating point and complex numbers. It will always print a - decimal point - for %e, %E, %f, %F, %g - and %G; it will not remove trailing zeros - for %g and %G. -

- -
- -
hash/fnv
-
-

- The package now includes 128-bit FNV-1 and FNV-1a hash support with - New128 and - New128a, respectively. -

- -
- -
html/template
-
-

- The package now reports an error if a predefined escaper (one of - "html", "urlquery" and "js") is found in a pipeline and does not match - what the auto-escaper would have decided on its own. - This avoids certain security or correctness issues. - Now use of one of these escapers is always either a no-op or an error. - (The no-op case eases migration from text/template.) -

- -
- -
image
-
-

- The Rectangle.Intersect - method now returns a zero Rectangle when called on - adjacent but non-overlapping rectangles, as documented. In - earlier releases it would incorrectly return an empty but - non-zero Rectangle. -

- -
- -
image/color
-
-

- The YCbCr to RGBA conversion formula has been tweaked to ensure - that rounding adjustments span the complete [0, 0xffff] RGBA - range. -

- -
- -
image/png
-
-

- The new Encoder.BufferPool - field allows specifying an EncoderBufferPool, - that will be used by the encoder to get temporary EncoderBuffer - buffers when encoding a PNG image. - - The use of a BufferPool reduces the number of - memory allocations performed while encoding multiple images. -

- -

- The package now supports the decoding of transparent 8-bit - grayscale ("Gray8") images. -

- -
- -
math/big
-
-

- The new - IsInt64 - and - IsUint64 - methods report whether an Int - may be represented as an int64 or uint64 - value. -

- -
- -
mime/multipart
-
-

- The new - FileHeader.Size - field describes the size of a file in a multipart message. -

- -
- -
net
-
-

- The new - Resolver.StrictErrors - provides control over how Go's built-in DNS resolver handles - temporary errors during queries composed of multiple sub-queries, - such as an A+AAAA address lookup. -

- -

- The new - Resolver.Dial - allows a Resolver to use a custom dial function. -

- -

- JoinHostPort now only places an address in square brackets if the host contains a colon. - In previous releases it would also wrap addresses in square brackets if they contained a percent ('%') sign. -

- -

- The new methods - TCPConn.SyscallConn, - IPConn.SyscallConn, - UDPConn.SyscallConn, - and - UnixConn.SyscallConn - provide access to the connections' underlying file descriptors. -

- -

- It is now safe to call Dial with the address obtained from - (*TCPListener).String() after creating the listener with - Listen("tcp", ":0"). - Previously it failed on some machines with half-configured IPv6 stacks. -

- -
- -
net/http
-
- -

- The Cookie.String method, used for - Cookie and Set-Cookie headers, now encloses values in double quotes - if the value contains either a space or a comma. -

- -

Server changes:

-
    -
  • - ServeMux now ignores ports in the host - header when matching handlers. The host is matched unmodified for CONNECT requests. -
  • - -
  • - The new Server.ServeTLS method wraps - Server.Serve with added TLS support. -
  • - -
  • - Server.WriteTimeout - now applies to HTTP/2 connections and is enforced per-stream. -
  • - -
  • - HTTP/2 now uses the priority write scheduler by default. - Frames are scheduled by following HTTP/2 priorities as described in - RFC 7540 Section 5.3. -
  • - -
  • - The HTTP handler returned by StripPrefix - now calls its provided handler with a modified clone of the original *http.Request. - Any code storing per-request state in maps keyed by *http.Request should - use - Request.Context, - Request.WithContext, - and - context.WithValue instead. -
  • - -
  • - LocalAddrContextKey now contains - the connection's actual network address instead of the interface address used by the listener. -
  • -
- -

Client & Transport changes:

-
    -
  • - The Transport - now supports making requests via SOCKS5 proxy when the URL returned by - Transport.Proxy - has the scheme socks5. -
  • -
- -
- -
net/http/fcgi
-
-

- The new - ProcessEnv - function returns FastCGI environment variables associated with an HTTP request - for which there are no appropriate - http.Request - fields, such as REMOTE_USER. -

- -
- -
net/http/httptest
-
-

- The new - Server.Client - method returns an HTTP client configured for making requests to the test server. -

- -

- The new - Server.Certificate - method returns the test server's TLS certificate, if any. -

- -
- -
net/http/httputil
-
-

- The ReverseProxy - now proxies all HTTP/2 response trailers, even those not declared in the initial response - header. Such undeclared trailers are used by the gRPC protocol. -

- -
- -
os
-
-

- The os package now uses the internal runtime poller - for file I/O. - This reduces the number of threads required for read/write - operations on pipes, and it eliminates races when one goroutine - closes a file while another is using the file for I/O. -

- -
-

- On Windows, - Args - is now populated without shell32.dll, improving process start-up time by 1-7 ms. -

- -
- -
os/exec
-
-

- The os/exec package now prevents child processes from being created with - any duplicate environment variables. - If Cmd.Env - contains duplicate environment keys, only the last - value in the slice for each duplicate key is used. -

- -
- -
os/user
-
-

- Lookup and - LookupId now - work on Unix systems when CGO_ENABLED=0 by reading - the /etc/passwd file. -

- -

- LookupGroup and - LookupGroupId now - work on Unix systems when CGO_ENABLED=0 by reading - the /etc/group file. -

- -
- -
reflect
-
-

- The new - MakeMapWithSize - function creates a map with a capacity hint. -

- -
- -
runtime
-
-

- Tracebacks generated by the runtime and recorded in profiles are - now accurate in the presence of inlining. - To retrieve tracebacks programmatically, applications should use - runtime.CallersFrames - rather than directly iterating over the results of - runtime.Callers. -

- -

- On Windows, Go no longer forces the system timer to run at high - resolution when the program is idle. - This should reduce the impact of Go programs on battery life. -

- -

- On FreeBSD, GOMAXPROCS and - runtime.NumCPU - are now based on the process' CPU mask, rather than the total - number of CPUs. -

- -

- The runtime has preliminary support for Android O. -

- -
- -
runtime/debug
-
-

- Calling - SetGCPercent - with a negative value no longer runs an immediate garbage collection. -

- -
- -
runtime/trace
-
-

- The execution trace now displays mark assist events, which - indicate when an application goroutine is forced to assist - garbage collection because it is allocating too quickly. -

- -

- "Sweep" events now encompass the entire process of finding free - space for an allocation, rather than recording each individual - span that is swept. - This reduces allocation latency when tracing allocation-heavy - programs. - The sweep event shows how many bytes were swept and how many - were reclaimed. -

- -
- -
sync
-
-

- Mutex is now more fair. -

- -
- -
syscall
-
-

- The new field - Credential.NoSetGroups - controls whether Unix systems make a setgroups system call - to set supplementary groups when starting a new process. -

- -

- The new field - SysProcAttr.AmbientCaps - allows setting ambient capabilities on Linux 4.3+ when creating - a new process. -

- -

- On 64-bit x86 Linux, process creation latency has been optimized with - use of CLONE_VFORK and CLONE_VM. -

- -

- The new - Conn - interface describes some types in the - net - package that can provide access to their underlying file descriptor - using the new - RawConn - interface. -

- -
- - -
testing/quick
-
-

- The package now chooses values in the full range when - generating int64 and uint64 random - numbers; in earlier releases generated values were always - limited to the [-262, 262) range. -

- -

- In previous releases, using a nil - Config.Rand - value caused a fixed deterministic random number generator to be used. - It now uses a random number generator seeded with the current time. - For the old behavior, set Config.Rand to rand.New(rand.NewSource(0)). -

- -
- -
text/template
-
-

- The handling of empty blocks, which was broken by a Go 1.8 - change that made the result dependent on the order of templates, - has been fixed, restoring the old Go 1.7 behavior. -

- -
- -
time
-
-

- The new methods - Duration.Round - and - Duration.Truncate - handle rounding and truncating durations to multiples of a given duration. -

- -

- Retrieving the time and sleeping now work correctly under Wine. -

- -

- If a Time value has a monotonic clock reading, its - string representation (as returned by String) now includes a - final field "m=±value", where value is the - monotonic clock reading formatted as a decimal number of seconds. -

- -

- The included tzdata timezone database has been - updated to version 2017b. As always, it is only used if the - system does not already have the database available. -

- -
diff --git a/doc/go1.html b/doc/go1.html deleted file mode 100644 index 939ee24df5..0000000000 --- a/doc/go1.html +++ /dev/null @@ -1,2038 +0,0 @@ - - -

Introduction to Go 1

- -

-Go version 1, Go 1 for short, defines a language and a set of core libraries -that provide a stable foundation for creating reliable products, projects, and -publications. -

- -

-The driving motivation for Go 1 is stability for its users. People should be able to -write Go programs and expect that they will continue to compile and run without -change, on a time scale of years, including in production environments such as -Google App Engine. Similarly, people should be able to write books about Go, be -able to say which version of Go the book is describing, and have that version -number still be meaningful much later. -

- -

-Code that compiles in Go 1 should, with few exceptions, continue to compile and -run throughout the lifetime of that version, even as we issue updates and bug -fixes such as Go version 1.1, 1.2, and so on. Other than critical fixes, changes -made to the language and library for subsequent releases of Go 1 may -add functionality but will not break existing Go 1 programs. -The Go 1 compatibility document -explains the compatibility guidelines in more detail. -

- -

-Go 1 is a representation of Go as it used today, not a wholesale rethinking of -the language. We avoided designing new features and instead focused on cleaning -up problems and inconsistencies and improving portability. There are a number -changes to the Go language and packages that we had considered for some time and -prototyped but not released primarily because they are significant and -backwards-incompatible. Go 1 was an opportunity to get them out, which is -helpful for the long term, but also means that Go 1 introduces incompatibilities -for old programs. Fortunately, the go fix tool can -automate much of the work needed to bring programs up to the Go 1 standard. -

- -

-This document outlines the major changes in Go 1 that will affect programmers -updating existing code; its reference point is the prior release, r60 (tagged as -r60.3). It also explains how to update code from r60 to run under Go 1. -

- -

Changes to the language

- -

Append

- -

-The append predeclared variadic function makes it easy to grow a slice -by adding elements to the end. -A common use is to add bytes to the end of a byte slice when generating output. -However, append did not provide a way to append a string to a []byte, -which is another common case. -

- -{{code "/doc/progs/go1.go" `/greeting := ..byte/` `/append.*hello/`}} - -

-By analogy with the similar property of copy, Go 1 -permits a string to be appended (byte-wise) directly to a byte -slice, reducing the friction between strings and byte slices. -The conversion is no longer necessary: -

- -{{code "/doc/progs/go1.go" `/append.*world/`}} - -

-Updating: -This is a new feature, so existing code needs no changes. -

- -

Close

- -

-The close predeclared function provides a mechanism -for a sender to signal that no more values will be sent. -It is important to the implementation of for range -loops over channels and is helpful in other situations. -Partly by design and partly because of race conditions that can occur otherwise, -it is intended for use only by the goroutine sending on the channel, -not by the goroutine receiving data. -However, before Go 1 there was no compile-time checking that close -was being used correctly. -

- -

-To close this gap, at least in part, Go 1 disallows close on receive-only channels. -Attempting to close such a channel is a compile-time error. -

- -
-    var c chan int
-    var csend chan<- int = c
-    var crecv <-chan int = c
-    close(c)     // legal
-    close(csend) // legal
-    close(crecv) // illegal
-
- -

-Updating: -Existing code that attempts to close a receive-only channel was -erroneous even before Go 1 and should be fixed. The compiler will -now reject such code. -

- -

Composite literals

- -

-In Go 1, a composite literal of array, slice, or map type can elide the -type specification for the elements' initializers if they are of pointer type. -All four of the initializations in this example are legal; the last one was illegal before Go 1. -

- -{{code "/doc/progs/go1.go" `/type Date struct/` `/STOP/`}} - -

-Updating: -This change has no effect on existing code, but the command -gofmt -s applied to existing source -will, among other things, elide explicit element types wherever permitted. -

- - -

Goroutines during init

- -

-The old language defined that go statements executed during initialization created goroutines but that they did not begin to run until initialization of the entire program was complete. -This introduced clumsiness in many places and, in effect, limited the utility -of the init construct: -if it was possible for another package to use the library during initialization, the library -was forced to avoid goroutines. -This design was done for reasons of simplicity and safety but, -as our confidence in the language grew, it seemed unnecessary. -Running goroutines during initialization is no more complex or unsafe than running them during normal execution. -

- -

-In Go 1, code that uses goroutines can be called from -init routines and global initialization expressions -without introducing a deadlock. -

- -{{code "/doc/progs/go1.go" `/PackageGlobal/` `/^}/`}} - -

-Updating: -This is a new feature, so existing code needs no changes, -although it's possible that code that depends on goroutines not starting before main will break. -There was no such code in the standard repository. -

- -

The rune type

- -

-The language spec allows the int type to be 32 or 64 bits wide, but current implementations set int to 32 bits even on 64-bit platforms. -It would be preferable to have int be 64 bits on 64-bit platforms. -(There are important consequences for indexing large slices.) -However, this change would waste space when processing Unicode characters with -the old language because the int type was also used to hold Unicode code points: each code point would waste an extra 32 bits of storage if int grew from 32 bits to 64. -

- -

-To make changing to 64-bit int feasible, -Go 1 introduces a new basic type, rune, to represent -individual Unicode code points. -It is an alias for int32, analogous to byte -as an alias for uint8. -

- -

-Character literals such as 'a', '語', and '\u0345' -now have default type rune, -analogous to 1.0 having default type float64. -A variable initialized to a character constant will therefore -have type rune unless otherwise specified. -

- -

-Libraries have been updated to use rune rather than int -when appropriate. For instance, the functions unicode.ToLower and -relatives now take and return a rune. -

- -{{code "/doc/progs/go1.go" `/STARTRUNE/` `/ENDRUNE/`}} - -

-Updating: -Most source code will be unaffected by this because the type inference from -:= initializers introduces the new type silently, and it propagates -from there. -Some code may get type errors that a trivial conversion will resolve. -

- -

The error type

- -

-Go 1 introduces a new built-in type, error, which has the following definition: -

- -
-    type error interface {
-        Error() string
-    }
-
- -

-Since the consequences of this type are all in the package library, -it is discussed below. -

- -

Deleting from maps

- -

-In the old language, to delete the entry with key k from map m, one wrote the statement, -

- -
-    m[k] = value, false
-
- -

-This syntax was a peculiar special case, the only two-to-one assignment. -It required passing a value (usually ignored) that is evaluated but discarded, -plus a boolean that was nearly always the constant false. -It did the job but was odd and a point of contention. -

- -

-In Go 1, that syntax has gone; instead there is a new built-in -function, delete. The call -

- -{{code "/doc/progs/go1.go" `/delete\(m, k\)/`}} - -

-will delete the map entry retrieved by the expression m[k]. -There is no return value. Deleting a non-existent entry is a no-op. -

- -

-Updating: -Running go fix will convert expressions of the form m[k] = value, -false into delete(m, k) when it is clear that -the ignored value can be safely discarded from the program and -false refers to the predefined boolean constant. -The fix tool -will flag other uses of the syntax for inspection by the programmer. -

- -

Iterating in maps

- -

-The old language specification did not define the order of iteration for maps, -and in practice it differed across hardware platforms. -This caused tests that iterated over maps to be fragile and non-portable, with the -unpleasant property that a test might always pass on one machine but break on another. -

- -

-In Go 1, the order in which elements are visited when iterating -over a map using a for range statement -is defined to be unpredictable, even if the same loop is run multiple -times with the same map. -Code should not assume that the elements are visited in any particular order. -

- -

-This change means that code that depends on iteration order is very likely to break early and be fixed long before it becomes a problem. -Just as important, it allows the map implementation to ensure better map balancing even when programs are using range loops to select an element from a map. -

- -{{code "/doc/progs/go1.go" `/Sunday/` `/^ }/`}} - -

-Updating: -This is one change where tools cannot help. Most existing code -will be unaffected, but some programs may break or misbehave; we -recommend manual checking of all range statements over maps to -verify they do not depend on iteration order. There were a few such -examples in the standard repository; they have been fixed. -Note that it was already incorrect to depend on the iteration order, which -was unspecified. This change codifies the unpredictability. -

- -

Multiple assignment

- -

-The language specification has long guaranteed that in assignments -the right-hand-side expressions are all evaluated before any left-hand-side expressions are assigned. -To guarantee predictable behavior, -Go 1 refines the specification further. -

- -

-If the left-hand side of the assignment -statement contains expressions that require evaluation, such as -function calls or array indexing operations, these will all be done -using the usual left-to-right rule before any variables are assigned -their value. Once everything is evaluated, the actual assignments -proceed in left-to-right order. -

- -

-These examples illustrate the behavior. -

- -{{code "/doc/progs/go1.go" `/sa :=/` `/then sc.0. = 2/`}} - -

-Updating: -This is one change where tools cannot help, but breakage is unlikely. -No code in the standard repository was broken by this change, and code -that depended on the previous unspecified behavior was already incorrect. -

- -

Returns and shadowed variables

- -

-A common mistake is to use return (without arguments) after an assignment to a variable that has the same name as a result variable but is not the same variable. -This situation is called shadowing: the result variable has been shadowed by another variable with the same name declared in an inner scope. -

- -

-In functions with named return values, -the Go 1 compilers disallow return statements without arguments if any of the named return values is shadowed at the point of the return statement. -(It isn't part of the specification, because this is one area we are still exploring; -the situation is analogous to the compilers rejecting functions that do not end with an explicit return statement.) -

- -

-This function implicitly returns a shadowed return value and will be rejected by the compiler: -

- -
-    func Bug() (i, j, k int) {
-        for i = 0; i < 5; i++ {
-            for j := 0; j < 5; j++ { // Redeclares j.
-                k += i*j
-                if k > 100 {
-                    return // Rejected: j is shadowed here.
-                }
-            }
-        }
-        return // OK: j is not shadowed here.
-    }
-
- -

-Updating: -Code that shadows return values in this way will be rejected by the compiler and will need to be fixed by hand. -The few cases that arose in the standard repository were mostly bugs. -

- -

Copying structs with unexported fields

- -

-The old language did not allow a package to make a copy of a struct value containing unexported fields belonging to a different package. -There was, however, a required exception for a method receiver; -also, the implementations of copy and append have never honored the restriction. -

- -

-Go 1 will allow packages to copy struct values containing unexported fields from other packages. -Besides resolving the inconsistency, -this change admits a new kind of API: a package can return an opaque value without resorting to a pointer or interface. -The new implementations of time.Time and -reflect.Value are examples of types taking advantage of this new property. -

- -

-As an example, if package p includes the definitions, -

- -
-    type Struct struct {
-        Public int
-        secret int
-    }
-    func NewStruct(a int) Struct {  // Note: not a pointer.
-        return Struct{a, f(a)}
-    }
-    func (s Struct) String() string {
-        return fmt.Sprintf("{%d (secret %d)}", s.Public, s.secret)
-    }
-
- -

-a package that imports p can assign and copy values of type -p.Struct at will. -Behind the scenes the unexported fields will be assigned and copied just -as if they were exported, -but the client code will never be aware of them. The code -

- -
-    import "p"
-
-    myStruct := p.NewStruct(23)
-    copyOfMyStruct := myStruct
-    fmt.Println(myStruct, copyOfMyStruct)
-
- -

-will show that the secret field of the struct has been copied to the new value. -

- -

-Updating: -This is a new feature, so existing code needs no changes. -

- -

Equality

- -

-Before Go 1, the language did not define equality on struct and array values. -This meant, -among other things, that structs and arrays could not be used as map keys. -On the other hand, Go did define equality on function and map values. -Function equality was problematic in the presence of closures -(when are two closures equal?) -while map equality compared pointers, not the maps' content, which was usually -not what the user would want. -

- -

-Go 1 addressed these issues. -First, structs and arrays can be compared for equality and inequality -(== and !=), -and therefore be used as map keys, -provided they are composed from elements for which equality is also defined, -using element-wise comparison. -

- -{{code "/doc/progs/go1.go" `/type Day struct/` `/Printf/`}} - -

-Second, Go 1 removes the definition of equality for function values, -except for comparison with nil. -Finally, map equality is gone too, also except for comparison with nil. -

- -

-Note that equality is still undefined for slices, for which the -calculation is in general infeasible. Also note that the ordered -comparison operators (< <= -> >=) are still undefined for -structs and arrays. - -

-Updating: -Struct and array equality is a new feature, so existing code needs no changes. -Existing code that depends on function or map equality will be -rejected by the compiler and will need to be fixed by hand. -Few programs will be affected, but the fix may require some -redesign. -

- -

The package hierarchy

- -

-Go 1 addresses many deficiencies in the old standard library and -cleans up a number of packages, making them more internally consistent -and portable. -

- -

-This section describes how the packages have been rearranged in Go 1. -Some have moved, some have been renamed, some have been deleted. -New packages are described in later sections. -

- -

The package hierarchy

- -

-Go 1 has a rearranged package hierarchy that groups related items -into subdirectories. For instance, utf8 and -utf16 now occupy subdirectories of unicode. -Also, some packages have moved into -subrepositories of -code.google.com/p/go -while others have been deleted outright. -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Old pathNew path

asn1 encoding/asn1
csv encoding/csv
gob encoding/gob
json encoding/json
xml encoding/xml

exp/template/html html/template

big math/big
cmath math/cmplx
rand math/rand

http net/http
http/cgi net/http/cgi
http/fcgi net/http/fcgi
http/httptest net/http/httptest
http/pprof net/http/pprof
mail net/mail
rpc net/rpc
rpc/jsonrpc net/rpc/jsonrpc
smtp net/smtp
url net/url

exec os/exec

scanner text/scanner
tabwriter text/tabwriter
template text/template
template/parse text/template/parse

utf8 unicode/utf8
utf16 unicode/utf16
- -

-Note that the package names for the old cmath and -exp/template/html packages have changed to cmplx -and template. -

- -

-Updating: -Running go fix will update all imports and package renames for packages that -remain inside the standard repository. Programs that import packages -that are no longer in the standard repository will need to be edited -by hand. -

- -

The package tree exp

- -

-Because they are not standardized, the packages under the exp directory will not be available in the -standard Go 1 release distributions, although they will be available in source code form -in the repository for -developers who wish to use them. -

- -

-Several packages have moved under exp at the time of Go 1's release: -

- -
    -
  • ebnf
  • -
  • html
  • -
  • go/types
  • -
- -

-(The EscapeString and UnescapeString types remain -in package html.) -

- -

-All these packages are available under the same names, with the prefix exp/: exp/ebnf etc. -

- -

-Also, the utf8.String type has been moved to its own package, exp/utf8string. -

- -

-Finally, the gotype command now resides in exp/gotype, while -ebnflint is now in exp/ebnflint. -If they are installed, they now reside in $GOROOT/bin/tool. -

- -

-Updating: -Code that uses packages in exp will need to be updated by hand, -or else compiled from an installation that has exp available. -The go fix tool or the compiler will complain about such uses. -

- -

The package tree old

- -

-Because they are deprecated, the packages under the old directory will not be available in the -standard Go 1 release distributions, although they will be available in source code form for -developers who wish to use them. -

- -

-The packages in their new locations are: -

- -
    -
  • old/netchan
  • -
- -

-Updating: -Code that uses packages now in old will need to be updated by hand, -or else compiled from an installation that has old available. -The go fix tool will warn about such uses. -

- -

Deleted packages

- -

-Go 1 deletes several packages outright: -

- -
    -
  • container/vector
  • -
  • exp/datafmt
  • -
  • go/typechecker
  • -
  • old/regexp
  • -
  • old/template
  • -
  • try
  • -
- -

-and also the command gotry. -

- -

-Updating: -Code that uses container/vector should be updated to use -slices directly. See -the Go -Language Community Wiki for some suggestions. -Code that uses the other packages (there should be almost zero) will need to be rethought. -

- -

Packages moving to subrepositories

- -

-Go 1 has moved a number of packages into other repositories, usually sub-repositories of -the main Go repository. -This table lists the old and new import paths: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
OldNew

crypto/bcrypt code.google.com/p/go.crypto/bcrypt
crypto/blowfish code.google.com/p/go.crypto/blowfish
crypto/cast5 code.google.com/p/go.crypto/cast5
crypto/md4 code.google.com/p/go.crypto/md4
crypto/ocsp code.google.com/p/go.crypto/ocsp
crypto/openpgp code.google.com/p/go.crypto/openpgp
crypto/openpgp/armor code.google.com/p/go.crypto/openpgp/armor
crypto/openpgp/elgamal code.google.com/p/go.crypto/openpgp/elgamal
crypto/openpgp/errors code.google.com/p/go.crypto/openpgp/errors
crypto/openpgp/packet code.google.com/p/go.crypto/openpgp/packet
crypto/openpgp/s2k code.google.com/p/go.crypto/openpgp/s2k
crypto/ripemd160 code.google.com/p/go.crypto/ripemd160
crypto/twofish code.google.com/p/go.crypto/twofish
crypto/xtea code.google.com/p/go.crypto/xtea
exp/ssh code.google.com/p/go.crypto/ssh

image/bmp code.google.com/p/go.image/bmp
image/tiff code.google.com/p/go.image/tiff

net/dict code.google.com/p/go.net/dict
net/websocket code.google.com/p/go.net/websocket
exp/spdy code.google.com/p/go.net/spdy

encoding/git85 code.google.com/p/go.codereview/git85
patch code.google.com/p/go.codereview/patch

exp/wingui code.google.com/p/gowingui
- -

-Updating: -Running go fix will update imports of these packages to use the new import paths. -Installations that depend on these packages will need to install them using -a go get command. -

- -

Major changes to the library

- -

-This section describes significant changes to the core libraries, the ones that -affect the most programs. -

- -

The error type and errors package

- -

-The placement of os.Error in package os is mostly historical: errors first came up when implementing package os, and they seemed system-related at the time. -Since then it has become clear that errors are more fundamental than the operating system. For example, it would be nice to use Errors in packages that os depends on, like syscall. -Also, having Error in os introduces many dependencies on os that would otherwise not exist. -

- -

-Go 1 solves these problems by introducing a built-in error interface type and a separate errors package (analogous to bytes and strings) that contains utility functions. -It replaces os.NewError with -errors.New, -giving errors a more central place in the environment. -

- -

-So the widely-used String method does not cause accidental satisfaction -of the error interface, the error interface uses instead -the name Error for that method: -

- -
-    type error interface {
-        Error() string
-    }
-
- -

-The fmt library automatically invokes Error, as it already -does for String, for easy printing of error values. -

- -{{code "/doc/progs/go1.go" `/START ERROR EXAMPLE/` `/END ERROR EXAMPLE/`}} - -

-All standard packages have been updated to use the new interface; the old os.Error is gone. -

- -

-A new package, errors, contains the function -

- -
-func New(text string) error
-
- -

-to turn a string into an error. It replaces the old os.NewError. -

- -{{code "/doc/progs/go1.go" `/ErrSyntax/`}} - -

-Updating: -Running go fix will update almost all code affected by the change. -Code that defines error types with a String method will need to be updated -by hand to rename the methods to Error. -

- -

System call errors

- -

-The old syscall package, which predated os.Error -(and just about everything else), -returned errors as int values. -In turn, the os package forwarded many of these errors, such -as EINVAL, but using a different set of errors on each platform. -This behavior was unpleasant and unportable. -

- -

-In Go 1, the -syscall -package instead returns an error for system call errors. -On Unix, the implementation is done by a -syscall.Errno type -that satisfies error and replaces the old os.Errno. -

- -

-The changes affecting os.EINVAL and relatives are -described elsewhere. - -

-Updating: -Running go fix will update almost all code affected by the change. -Regardless, most code should use the os package -rather than syscall and so will be unaffected. -

- -

Time

- -

-Time is always a challenge to support well in a programming language. -The old Go time package had int64 units, no -real type safety, -and no distinction between absolute times and durations. -

- -

-One of the most sweeping changes in the Go 1 library is therefore a -complete redesign of the -time package. -Instead of an integer number of nanoseconds as an int64, -and a separate *time.Time type to deal with human -units such as hours and years, -there are now two fundamental types: -time.Time -(a value, so the * is gone), which represents a moment in time; -and time.Duration, -which represents an interval. -Both have nanosecond resolution. -A Time can represent any time into the ancient -past and remote future, while a Duration can -span plus or minus only about 290 years. -There are methods on these types, plus a number of helpful -predefined constant durations such as time.Second. -

- -

-Among the new methods are things like -Time.Add, -which adds a Duration to a Time, and -Time.Sub, -which subtracts two Times to yield a Duration. -

- -

-The most important semantic change is that the Unix epoch (Jan 1, 1970) is now -relevant only for those functions and methods that mention Unix: -time.Unix -and the Unix -and UnixNano methods -of the Time type. -In particular, -time.Now -returns a time.Time value rather than, in the old -API, an integer nanosecond count since the Unix epoch. -

- -{{code "/doc/progs/go1.go" `/sleepUntil/` `/^}/`}} - -

-The new types, methods, and constants have been propagated through -all the standard packages that use time, such as os and -its representation of file time stamps. -

- -

-Updating: -The go fix tool will update many uses of the old time package to use the new -types and methods, although it does not replace values such as 1e9 -representing nanoseconds per second. -Also, because of type changes in some of the values that arise, -some of the expressions rewritten by the fix tool may require -further hand editing; in such cases the rewrite will include -the correct function or method for the old functionality, but -may have the wrong type or require further analysis. -

- -

Minor changes to the library

- -

-This section describes smaller changes, such as those to less commonly -used packages or that affect -few programs beyond the need to run go fix. -This category includes packages that are new in Go 1. -Collectively they improve portability, regularize behavior, and -make the interfaces more modern and Go-like. -

- -

The archive/zip package

- -

-In Go 1, *zip.Writer no -longer has a Write method. Its presence was a mistake. -

- -

-Updating: -What little code is affected will be caught by the compiler and must be updated by hand. -

- -

The bufio package

- -

-In Go 1, bufio.NewReaderSize -and -bufio.NewWriterSize -functions no longer return an error for invalid sizes. -If the argument size is too small or invalid, it is adjusted. -

- -

-Updating: -Running go fix will update calls that assign the error to _. -Calls that aren't fixed will be caught by the compiler and must be updated by hand. -

- -

The compress/flate, compress/gzip and compress/zlib packages

- -

-In Go 1, the NewWriterXxx functions in -compress/flate, -compress/gzip and -compress/zlib -all return (*Writer, error) if they take a compression level, -and *Writer otherwise. Package gzip's -Compressor and Decompressor types have been renamed -to Writer and Reader. Package flate's -WrongValueError type has been removed. -

- -

-Updating -Running go fix will update old names and calls that assign the error to _. -Calls that aren't fixed will be caught by the compiler and must be updated by hand. -

- -

The crypto/aes and crypto/des packages

- -

-In Go 1, the Reset method has been removed. Go does not guarantee -that memory is not copied and therefore this method was misleading. -

- -

-The cipher-specific types *aes.Cipher, *des.Cipher, -and *des.TripleDESCipher have been removed in favor of -cipher.Block. -

- -

-Updating: -Remove the calls to Reset. Replace uses of the specific cipher types with -cipher.Block. -

- -

The crypto/elliptic package

- -

-In Go 1, elliptic.Curve -has been made an interface to permit alternative implementations. The curve -parameters have been moved to the -elliptic.CurveParams -structure. -

- -

-Updating: -Existing users of *elliptic.Curve will need to change to -simply elliptic.Curve. Calls to Marshal, -Unmarshal and GenerateKey are now functions -in crypto/elliptic that take an elliptic.Curve -as their first argument. -

- -

The crypto/hmac package

- -

-In Go 1, the hash-specific functions, such as hmac.NewMD5, have -been removed from crypto/hmac. Instead, hmac.New takes -a function that returns a hash.Hash, such as md5.New. -

- -

-Updating: -Running go fix will perform the needed changes. -

- -

The crypto/x509 package

- -

-In Go 1, the -CreateCertificate -function and -CreateCRL -method in crypto/x509 have been altered to take an -interface{} where they previously took a *rsa.PublicKey -or *rsa.PrivateKey. This will allow other public key algorithms -to be implemented in the future. -

- -

-Updating: -No changes will be needed. -

- -

The encoding/binary package

- -

-In Go 1, the binary.TotalSize function has been replaced by -Size, -which takes an interface{} argument rather than -a reflect.Value. -

- -

-Updating: -What little code is affected will be caught by the compiler and must be updated by hand. -

- -

The encoding/xml package

- -

-In Go 1, the xml package -has been brought closer in design to the other marshaling packages such -as encoding/gob. -

- -

-The old Parser type is renamed -Decoder and has a new -Decode method. An -Encoder type was also introduced. -

- -

-The functions Marshal -and Unmarshal -work with []byte values now. To work with streams, -use the new Encoder -and Decoder types. -

- -

-When marshaling or unmarshaling values, the format of supported flags in -field tags has changed to be closer to the -json package -(`xml:"name,flag"`). The matching done between field tags, field -names, and the XML attribute and element names is now case-sensitive. -The XMLName field tag, if present, must also match the name -of the XML element being marshaled. -

- -

-Updating: -Running go fix will update most uses of the package except for some calls to -Unmarshal. Special care must be taken with field tags, -since the fix tool will not update them and if not fixed by hand they will -misbehave silently in some cases. For example, the old -"attr" is now written ",attr" while plain -"attr" remains valid but with a different meaning. -

- -

The expvar package

- -

-In Go 1, the RemoveAll function has been removed. -The Iter function and Iter method on *Map have -been replaced by -Do -and -(*Map).Do. -

- -

-Updating: -Most code using expvar will not need changing. The rare code that used -Iter can be updated to pass a closure to Do to achieve the same effect. -

- -

The flag package

- -

-In Go 1, the interface flag.Value has changed slightly. -The Set method now returns an error instead of -a bool to indicate success or failure. -

- -

-There is also a new kind of flag, Duration, to support argument -values specifying time intervals. -Values for such flags must be given units, just as time.Duration -formats them: 10s, 1h30m, etc. -

- -{{code "/doc/progs/go1.go" `/timeout/`}} - -

-Updating: -Programs that implement their own flags will need minor manual fixes to update their -Set methods. -The Duration flag is new and affects no existing code. -

- - -

The go/* packages

- -

-Several packages under go have slightly revised APIs. -

- -

-A concrete Mode type was introduced for configuration mode flags -in the packages -go/scanner, -go/parser, -go/printer, and -go/doc. -

- -

-The modes AllowIllegalChars and InsertSemis have been removed -from the go/scanner package. They were mostly -useful for scanning text other then Go source files. Instead, the -text/scanner package should be used -for that purpose. -

- -

-The ErrorHandler provided -to the scanner's Init method is -now simply a function rather than an interface. The ErrorVector type has -been removed in favor of the (existing) ErrorList -type, and the ErrorVector methods have been migrated. Instead of embedding -an ErrorVector in a client of the scanner, now a client should maintain -an ErrorList. -

- -

-The set of parse functions provided by the go/parser -package has been reduced to the primary parse function -ParseFile, and a couple of -convenience functions ParseDir -and ParseExpr. -

- -

-The go/printer package supports an additional -configuration mode SourcePos; -if set, the printer will emit //line comments such that the generated -output contains the original source code position information. The new type -CommentedNode can be -used to provide comments associated with an arbitrary -ast.Node (until now only -ast.File carried comment information). -

- -

-The type names of the go/doc package have been -streamlined by removing the Doc suffix: PackageDoc -is now Package, ValueDoc is Value, etc. -Also, all types now consistently have a Name field (or Names, -in the case of type Value) and Type.Factories has become -Type.Funcs. -Instead of calling doc.NewPackageDoc(pkg, importpath), -documentation for a package is created with: -

- -
-    doc.New(pkg, importpath, mode)
-
- -

-where the new mode parameter specifies the operation mode: -if set to AllDecls, all declarations -(not just exported ones) are considered. -The function NewFileDoc was removed, and the function -CommentText has become the method -Text of -ast.CommentGroup. -

- -

-In package go/token, the -token.FileSet method Files -(which originally returned a channel of *token.Files) has been replaced -with the iterator Iterate that -accepts a function argument instead. -

- -

-In package go/build, the API -has been nearly completely replaced. -The package still computes Go package information -but it does not run the build: the Cmd and Script -types are gone. -(To build code, use the new -go command instead.) -The DirInfo type is now named -Package. -FindTree and ScanDir are replaced by -Import -and -ImportDir. -

- -

-Updating: -Code that uses packages in go will have to be updated by hand; the -compiler will reject incorrect uses. Templates used in conjunction with any of the -go/doc types may need manual fixes; the renamed fields will lead -to run-time errors. -

- -

The hash package

- -

-In Go 1, the definition of hash.Hash includes -a new method, BlockSize. This new method is used primarily in the -cryptographic libraries. -

- -

-The Sum method of the -hash.Hash interface now takes a -[]byte argument, to which the hash value will be appended. -The previous behavior can be recreated by adding a nil argument to the call. -

- -

-Updating: -Existing implementations of hash.Hash will need to add a -BlockSize method. Hashes that process the input one byte at -a time can implement BlockSize to return 1. -Running go fix will update calls to the Sum methods of the various -implementations of hash.Hash. -

- -

-Updating: -Since the package's functionality is new, no updating is necessary. -

- -

The http package

- -

-In Go 1 the http package is refactored, -putting some of the utilities into a -httputil subdirectory. -These pieces are only rarely needed by HTTP clients. -The affected items are: -

- -
    -
  • ClientConn
  • -
  • DumpRequest
  • -
  • DumpRequestOut
  • -
  • DumpResponse
  • -
  • NewChunkedReader
  • -
  • NewChunkedWriter
  • -
  • NewClientConn
  • -
  • NewProxyClientConn
  • -
  • NewServerConn
  • -
  • NewSingleHostReverseProxy
  • -
  • ReverseProxy
  • -
  • ServerConn
  • -
- -

-The Request.RawURL field has been removed; it was a -historical artifact. -

- -

-The Handle and HandleFunc -functions, and the similarly-named methods of ServeMux, -now panic if an attempt is made to register the same pattern twice. -

- -

-Updating: -Running go fix will update the few programs that are affected except for -uses of RawURL, which must be fixed by hand. -

- -

The image package

- -

-The image package has had a number of -minor changes, rearrangements and renamings. -

- -

-Most of the color handling code has been moved into its own package, -image/color. -For the elements that moved, a symmetry arises; for instance, -each pixel of an -image.RGBA -is a -color.RGBA. -

- -

-The old image/ycbcr package has been folded, with some -renamings, into the -image -and -image/color -packages. -

- -

-The old image.ColorImage type is still in the image -package but has been renamed -image.Uniform, -while image.Tiled has been removed. -

- -

-This table lists the renamings. -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
OldNew

image.Color color.Color
image.ColorModel color.Model
image.ColorModelFunc color.ModelFunc
image.PalettedColorModel color.Palette

image.RGBAColor color.RGBA
image.RGBA64Color color.RGBA64
image.NRGBAColor color.NRGBA
image.NRGBA64Color color.NRGBA64
image.AlphaColor color.Alpha
image.Alpha16Color color.Alpha16
image.GrayColor color.Gray
image.Gray16Color color.Gray16

image.RGBAColorModel color.RGBAModel
image.RGBA64ColorModel color.RGBA64Model
image.NRGBAColorModel color.NRGBAModel
image.NRGBA64ColorModel color.NRGBA64Model
image.AlphaColorModel color.AlphaModel
image.Alpha16ColorModel color.Alpha16Model
image.GrayColorModel color.GrayModel
image.Gray16ColorModel color.Gray16Model

ycbcr.RGBToYCbCr color.RGBToYCbCr
ycbcr.YCbCrToRGB color.YCbCrToRGB
ycbcr.YCbCrColorModel color.YCbCrModel
ycbcr.YCbCrColor color.YCbCr
ycbcr.YCbCr image.YCbCr

ycbcr.SubsampleRatio444 image.YCbCrSubsampleRatio444
ycbcr.SubsampleRatio422 image.YCbCrSubsampleRatio422
ycbcr.SubsampleRatio420 image.YCbCrSubsampleRatio420

image.ColorImage image.Uniform
- -

-The image package's New functions -(NewRGBA, -NewRGBA64, etc.) -take an image.Rectangle as an argument -instead of four integers. -

- -

-Finally, there are new predefined color.Color variables -color.Black, -color.White, -color.Opaque -and -color.Transparent. -

- -

-Updating: -Running go fix will update almost all code affected by the change. -

- -

The log/syslog package

- -

-In Go 1, the syslog.NewLogger -function returns an error as well as a log.Logger. -

- -

-Updating: -What little code is affected will be caught by the compiler and must be updated by hand. -

- -

The mime package

- -

-In Go 1, the FormatMediaType function -of the mime package has been simplified to make it -consistent with -ParseMediaType. -It now takes "text/html" rather than "text" and "html". -

- -

-Updating: -What little code is affected will be caught by the compiler and must be updated by hand. -

- -

The net package

- -

-In Go 1, the various SetTimeout, -SetReadTimeout, and SetWriteTimeout methods -have been replaced with -SetDeadline, -SetReadDeadline, and -SetWriteDeadline, -respectively. Rather than taking a timeout value in nanoseconds that -apply to any activity on the connection, the new methods set an -absolute deadline (as a time.Time value) after which -reads and writes will time out and no longer block. -

- -

-There are also new functions -net.DialTimeout -to simplify timing out dialing a network address and -net.ListenMulticastUDP -to allow multicast UDP to listen concurrently across multiple listeners. -The net.ListenMulticastUDP function replaces the old -JoinGroup and LeaveGroup methods. -

- -

-Updating: -Code that uses the old methods will fail to compile and must be updated by hand. -The semantic change makes it difficult for the fix tool to update automatically. -

- -

The os package

- -

-The Time function has been removed; callers should use -the Time type from the -time package. -

- -

-The Exec function has been removed; callers should use -Exec from the syscall package, where available. -

- -

-The ShellExpand function has been renamed to ExpandEnv. -

- -

-The NewFile function -now takes a uintptr fd, instead of an int. -The Fd method on files now -also returns a uintptr. -

- -

-There are no longer error constants such as EINVAL -in the os package, since the set of values varied with -the underlying operating system. There are new portable functions like -IsPermission -to test common error properties, plus a few new error values -with more Go-like names, such as -ErrPermission -and -ErrNotExist. -

- -

-The Getenverror function has been removed. To distinguish -between a non-existent environment variable and an empty string, -use os.Environ or -syscall.Getenv. -

- - -

-The Process.Wait method has -dropped its option argument and the associated constants are gone -from the package. -Also, the function Wait is gone; only the method of -the Process type persists. -

- -

-The Waitmsg type returned by -Process.Wait -has been replaced with a more portable -ProcessState -type with accessor methods to recover information about the -process. -Because of changes to Wait, the ProcessState -value always describes an exited process. -Portability concerns simplified the interface in other ways, but the values returned by the -ProcessState.Sys and -ProcessState.SysUsage -methods can be type-asserted to underlying system-specific data structures such as -syscall.WaitStatus and -syscall.Rusage on Unix. -

- -

-Updating: -Running go fix will drop a zero argument to Process.Wait. -All other changes will be caught by the compiler and must be updated by hand. -

- -

The os.FileInfo type

- -

-Go 1 redefines the os.FileInfo type, -changing it from a struct to an interface: -

- -
-    type FileInfo interface {
-        Name() string       // base name of the file
-        Size() int64        // length in bytes
-        Mode() FileMode     // file mode bits
-        ModTime() time.Time // modification time
-        IsDir() bool        // abbreviation for Mode().IsDir()
-        Sys() interface{}   // underlying data source (can return nil)
-    }
-
- -

-The file mode information has been moved into a subtype called -os.FileMode, -a simple integer type with IsDir, Perm, and String -methods. -

- -

-The system-specific details of file modes and properties such as (on Unix) -i-number have been removed from FileInfo altogether. -Instead, each operating system's os package provides an -implementation of the FileInfo interface, which -has a Sys method that returns the -system-specific representation of file metadata. -For instance, to discover the i-number of a file on a Unix system, unpack -the FileInfo like this: -

- -
-    fi, err := os.Stat("hello.go")
-    if err != nil {
-        log.Fatal(err)
-    }
-    // Check that it's a Unix file.
-    unixStat, ok := fi.Sys().(*syscall.Stat_t)
-    if !ok {
-        log.Fatal("hello.go: not a Unix file")
-    }
-    fmt.Printf("file i-number: %d\n", unixStat.Ino)
-
- -

-Assuming (which is unwise) that "hello.go" is a Unix file, -the i-number expression could be contracted to -

- -
-    fi.Sys().(*syscall.Stat_t).Ino
-
- -

-The vast majority of uses of FileInfo need only the methods -of the standard interface. -

- -

-The os package no longer contains wrappers for the POSIX errors -such as ENOENT. -For the few programs that need to verify particular error conditions, there are -now the boolean functions -IsExist, -IsNotExist -and -IsPermission. -

- -{{code "/doc/progs/go1.go" `/os\.Open/` `/}/`}} - -

-Updating: -Running go fix will update code that uses the old equivalent of the current os.FileInfo -and os.FileMode API. -Code that needs system-specific file details will need to be updated by hand. -Code that uses the old POSIX error values from the os package -will fail to compile and will also need to be updated by hand. -

- -

The os/signal package

- -

-The os/signal package in Go 1 replaces the -Incoming function, which returned a channel -that received all incoming signals, -with the selective Notify function, which asks -for delivery of specific signals on an existing channel. -

- -

-Updating: -Code must be updated by hand. -A literal translation of -

-
-c := signal.Incoming()
-
-

-is -

-
-c := make(chan os.Signal, 1)
-signal.Notify(c) // ask for all signals
-
-

-but most code should list the specific signals it wants to handle instead: -

-
-c := make(chan os.Signal, 1)
-signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT)
-
- -

The path/filepath package

- -

-In Go 1, the Walk function of the -path/filepath package -has been changed to take a function value of type -WalkFunc -instead of a Visitor interface value. -WalkFunc unifies the handling of both files and directories. -

- -
-    type WalkFunc func(path string, info os.FileInfo, err error) error
-
- -

-The WalkFunc function will be called even for files or directories that could not be opened; -in such cases the error argument will describe the failure. -If a directory's contents are to be skipped, -the function should return the value filepath.SkipDir -

- -{{code "/doc/progs/go1.go" `/STARTWALK/` `/ENDWALK/`}} - -

-Updating: -The change simplifies most code but has subtle consequences, so affected programs -will need to be updated by hand. -The compiler will catch code using the old interface. -

- -

The regexp package

- -

-The regexp package has been rewritten. -It has the same interface but the specification of the regular expressions -it supports has changed from the old "egrep" form to that of -RE2. -

- -

-Updating: -Code that uses the package should have its regular expressions checked by hand. -

- -

The runtime package

- -

-In Go 1, much of the API exported by package -runtime has been removed in favor of -functionality provided by other packages. -Code using the runtime.Type interface -or its specific concrete type implementations should -now use package reflect. -Code using runtime.Semacquire or runtime.Semrelease -should use channels or the abstractions in package sync. -The runtime.Alloc, runtime.Free, -and runtime.Lookup functions, an unsafe API created for -debugging the memory allocator, have no replacement. -

- -

-Before, runtime.MemStats was a global variable holding -statistics about memory allocation, and calls to runtime.UpdateMemStats -ensured that it was up to date. -In Go 1, runtime.MemStats is a struct type, and code should use -runtime.ReadMemStats -to obtain the current statistics. -

- -

-The package adds a new function, -runtime.NumCPU, that returns the number of CPUs available -for parallel execution, as reported by the operating system kernel. -Its value can inform the setting of GOMAXPROCS. -The runtime.Cgocalls and runtime.Goroutines functions -have been renamed to runtime.NumCgoCall and runtime.NumGoroutine. -

- -

-Updating: -Running go fix will update code for the function renamings. -Other code will need to be updated by hand. -

- -

The strconv package

- -

-In Go 1, the -strconv -package has been significantly reworked to make it more Go-like and less C-like, -although Atoi lives on (it's similar to -int(ParseInt(x, 10, 0)), as does -Itoa(x) (FormatInt(int64(x), 10)). -There are also new variants of some of the functions that append to byte slices rather than -return strings, to allow control over allocation. -

- -

-This table summarizes the renamings; see the -package documentation -for full details. -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Old callNew call

Atob(x) ParseBool(x)

Atof32(x) ParseFloat(x, 32)§
Atof64(x) ParseFloat(x, 64)
AtofN(x, n) ParseFloat(x, n)

Atoi(x) Atoi(x)
Atoi(x) ParseInt(x, 10, 0)§
Atoi64(x) ParseInt(x, 10, 64)

Atoui(x) ParseUint(x, 10, 0)§
Atoui64(x) ParseUint(x, 10, 64)

Btoi64(x, b) ParseInt(x, b, 64)
Btoui64(x, b) ParseUint(x, b, 64)

Btoa(x) FormatBool(x)

Ftoa32(x, f, p) FormatFloat(float64(x), f, p, 32)
Ftoa64(x, f, p) FormatFloat(x, f, p, 64)
FtoaN(x, f, p, n) FormatFloat(x, f, p, n)

Itoa(x) Itoa(x)
Itoa(x) FormatInt(int64(x), 10)
Itoa64(x) FormatInt(x, 10)

Itob(x, b) FormatInt(int64(x), b)
Itob64(x, b) FormatInt(x, b)

Uitoa(x) FormatUint(uint64(x), 10)
Uitoa64(x) FormatUint(x, 10)

Uitob(x, b) FormatUint(uint64(x), b)
Uitob64(x, b) FormatUint(x, b)
- -

-Updating: -Running go fix will update almost all code affected by the change. -
Atoi persists but Atoui and Atof32 do not, so -they may require -a cast that must be added by hand; the go fix tool will warn about it. -

- - -

The template packages

- -

-The template and exp/template/html packages have moved to -text/template and -html/template. -More significant, the interface to these packages has been simplified. -The template language is the same, but the concept of "template set" is gone -and the functions and methods of the packages have changed accordingly, -often by elimination. -

- -

-Instead of sets, a Template object -may contain multiple named template definitions, -in effect constructing -name spaces for template invocation. -A template can invoke any other template associated with it, but only those -templates associated with it. -The simplest way to associate templates is to parse them together, something -made easier with the new structure of the packages. -

- -

-Updating: -The imports will be updated by fix tool. -Single-template uses will be otherwise be largely unaffected. -Code that uses multiple templates in concert will need to be updated by hand. -The examples in -the documentation for text/template can provide guidance. -

- -

The testing package

- -

-The testing package has a type, B, passed as an argument to benchmark functions. -In Go 1, B has new methods, analogous to those of T, enabling -logging and failure reporting. -

- -{{code "/doc/progs/go1.go" `/func.*Benchmark/` `/^}/`}} - -

-Updating: -Existing code is unaffected, although benchmarks that use println -or panic should be updated to use the new methods. -

- -

The testing/script package

- -

-The testing/script package has been deleted. It was a dreg. -

- -

-Updating: -No code is likely to be affected. -

- -

The unsafe package

- -

-In Go 1, the functions -unsafe.Typeof, unsafe.Reflect, -unsafe.Unreflect, unsafe.New, and -unsafe.NewArray have been removed; -they duplicated safer functionality provided by -package reflect. -

- -

-Updating: -Code using these functions must be rewritten to use -package reflect. -The changes to encoding/gob and the protocol buffer library -may be helpful as examples. -

- -

The url package

- -

-In Go 1 several fields from the url.URL type -were removed or replaced. -

- -

-The String method now -predictably rebuilds an encoded URL string using all of URL's -fields as necessary. The resulting string will also no longer have -passwords escaped. -

- -

-The Raw field has been removed. In most cases the String -method may be used in its place. -

- -

-The old RawUserinfo field is replaced by the User -field, of type *net.Userinfo. -Values of this type may be created using the new net.User -and net.UserPassword -functions. The EscapeUserinfo and UnescapeUserinfo -functions are also gone. -

- -

-The RawAuthority field has been removed. The same information is -available in the Host and User fields. -

- -

-The RawPath field and the EncodedPath method have -been removed. The path information in rooted URLs (with a slash following the -schema) is now available only in decoded form in the Path field. -Occasionally, the encoded data may be required to obtain information that -was lost in the decoding process. These cases must be handled by accessing -the data the URL was built from. -

- -

-URLs with non-rooted paths, such as "mailto:dev@golang.org?subject=Hi", -are also handled differently. The OpaquePath boolean field has been -removed and a new Opaque string field introduced to hold the encoded -path for such URLs. In Go 1, the cited URL parses as: -

- -
-    URL{
-        Scheme: "mailto",
-        Opaque: "dev@golang.org",
-        RawQuery: "subject=Hi",
-    }
-
- -

-A new RequestURI method was -added to URL. -

- -

-The ParseWithReference function has been renamed to ParseWithFragment. -

- -

-Updating: -Code that uses the old fields will fail to compile and must be updated by hand. -The semantic changes make it difficult for the fix tool to update automatically. -

- -

The go command

- -

-Go 1 introduces the go command, a tool for fetching, -building, and installing Go packages and commands. The go command -does away with makefiles, instead using Go source code to find dependencies and -determine build conditions. Most existing Go programs will no longer require -makefiles to be built. -

- -

-See How to Write Go Code for a primer on the -go command and the go command documentation -for the full details. -

- -

-Updating: -Projects that depend on the Go project's old makefile-based build -infrastructure (Make.pkg, Make.cmd, and so on) should -switch to using the go command for building Go code and, if -necessary, rewrite their makefiles to perform any auxiliary build tasks. -

- -

The cgo command

- -

-In Go 1, the cgo command -uses a different _cgo_export.h -file, which is generated for packages containing //export lines. -The _cgo_export.h file now begins with the C preamble comment, -so that exported function definitions can use types defined there. -This has the effect of compiling the preamble multiple times, so a -package using //export must not put function definitions -or variable initializations in the C preamble. -

- -

Packaged releases

- -

-One of the most significant changes associated with Go 1 is the availability -of prepackaged, downloadable distributions. -They are available for many combinations of architecture and operating system -(including Windows) and the list will grow. -Installation details are described on the -Getting Started page, while -the distributions themselves are listed on the -downloads page. diff --git a/doc/go1compat.html b/doc/go1compat.html deleted file mode 100644 index a5624ef5f6..0000000000 --- a/doc/go1compat.html +++ /dev/null @@ -1,202 +0,0 @@ - - -

Introduction

-

-The release of Go version 1, Go 1 for short, is a major milestone -in the development of the language. Go 1 is a stable platform for -the growth of programs and projects written in Go. -

- -

-Go 1 defines two things: first, the specification of the language; -and second, the specification of a set of core APIs, the "standard -packages" of the Go library. The Go 1 release includes their -implementation in the form of two compiler suites (gc and gccgo), -and the core libraries themselves. -

- -

-It is intended that programs written to the Go 1 specification will -continue to compile and run correctly, unchanged, over the lifetime -of that specification. At some indefinite point, a Go 2 specification -may arise, but until that time, Go programs that work today should -continue to work even as future "point" releases of Go 1 arise (Go -1.1, Go 1.2, etc.). -

- -

-Compatibility is at the source level. Binary compatibility for -compiled packages is not guaranteed between releases. After a point -release, Go source will need to be recompiled to link against the -new release. -

- -

-The APIs may grow, acquiring new packages and features, but not in -a way that breaks existing Go 1 code. -

- -

Expectations

- -

-Although we expect that the vast majority of programs will maintain -this compatibility over time, it is impossible to guarantee that -no future change will break any program. This document is an attempt -to set expectations for the compatibility of Go 1 software in the -future. There are a number of ways in which a program that compiles -and runs today may fail to do so after a future point release. They -are all unlikely but worth recording. -

- -
    -
  • -Security. A security issue in the specification or implementation -may come to light whose resolution requires breaking compatibility. -We reserve the right to address such security issues. -
  • - -
  • -Unspecified behavior. The Go specification tries to be explicit -about most properties of the language, but there are some aspects -that are undefined. Programs that depend on such unspecified behavior -may break in future releases. -
  • - -
  • -Specification errors. If it becomes necessary to address an -inconsistency or incompleteness in the specification, resolving the -issue could affect the meaning or legality of existing programs. -We reserve the right to address such issues, including updating the -implementations. Except for security issues, no incompatible changes -to the specification would be made. -
  • - -
  • -Bugs. If a compiler or library has a bug that violates the -specification, a program that depends on the buggy behavior may -break if the bug is fixed. We reserve the right to fix such bugs. -
  • - -
  • -Struct literals. For the addition of features in later point -releases, it may be necessary to add fields to exported structs in -the API. Code that uses unkeyed struct literals (such as pkg.T{3, -"x"}) to create values of these types would fail to compile after -such a change. However, code that uses keyed literals (pkg.T{A: -3, B: "x"}) will continue to compile after such a change. We will -update such data structures in a way that allows keyed struct -literals to remain compatible, although unkeyed literals may fail -to compile. (There are also more intricate cases involving nested -data structures or interfaces, but they have the same resolution.) -We therefore recommend that composite literals whose type is defined -in a separate package should use the keyed notation. -
  • - -
  • -Methods. As with struct fields, it may be necessary to add methods -to types. -Under some circumstances, such as when the type is embedded in -a struct along with another type, -the addition of the new method may break -the struct by creating a conflict with an existing method of the other -embedded type. -We cannot protect against this rare case and do not guarantee compatibility -should it arise. -
  • - -
  • -Dot imports. If a program imports a standard package -using import . "path", additional names defined in the -imported package in future releases may conflict with other names -defined in the program. We do not recommend the use of import . -outside of tests, and using it may cause a program to fail -to compile in future releases. -
  • - -
  • -Use of package unsafe. Packages that import -unsafe -may depend on internal properties of the Go implementation. -We reserve the right to make changes to the implementation -that may break such programs. -
  • - -
- -

-Of course, for all of these possibilities, should they arise, we -would endeavor whenever feasible to update the specification, -compilers, or libraries without affecting existing code. -

- -

-These same considerations apply to successive point releases. For -instance, code that runs under Go 1.2 should be compatible with Go -1.2.1, Go 1.3, Go 1.4, etc., although not necessarily with Go 1.1 -since it may use features added only in Go 1.2 -

- -

-Features added between releases, available in the source repository -but not part of the numbered binary releases, are under active -development. No promise of compatibility is made for software using -such features until they have been released. -

- -

-Finally, although it is not a correctness issue, it is possible -that the performance of a program may be affected by -changes in the implementation of the compilers or libraries upon -which it depends. -No guarantee can be made about the performance of a -given program between releases. -

- -

-Although these expectations apply to Go 1 itself, we hope similar -considerations would be made for the development of externally -developed software based on Go 1. -

- -

Sub-repositories

- -

-Code in sub-repositories of the main go tree, such as -golang.org/x/net, -may be developed under -looser compatibility requirements. However, the sub-repositories -will be tagged as appropriate to identify versions that are compatible -with the Go 1 point releases. -

- -

Operating systems

- -

-It is impossible to guarantee long-term compatibility with operating -system interfaces, which are changed by outside parties. -The syscall package -is therefore outside the purview of the guarantees made here. -As of Go version 1.4, the syscall package is frozen. -Any evolution of the system call interface must be supported elsewhere, -such as in the -go.sys subrepository. -For details and background, see -this document. -

- -

Tools

- -

-Finally, the Go toolchain (compilers, linkers, build tools, and so -on) is under active development and may change behavior. This -means, for instance, that scripts that depend on the location and -properties of the tools may be broken by a point release. -

- -

-These caveats aside, we believe that Go 1 will be a firm foundation -for the development of Go and its ecosystem. -

diff --git a/doc/go_faq.html b/doc/go_faq.html deleted file mode 100644 index 67dc0b9bd4..0000000000 --- a/doc/go_faq.html +++ /dev/null @@ -1,2477 +0,0 @@ - - -

Origins

- -

-What is the purpose of the project?

- -

-At the time of Go's inception, only a decade ago, the programming world was different from today. -Production software was usually written in C++ or Java, -GitHub did not exist, most computers were not yet multiprocessors, -and other than Visual Studio and Eclipse there were few IDEs or other high-level tools available -at all, let alone for free on the Internet. -

- -

-Meanwhile, we had become frustrated by the undue complexity required to use -the languages we worked with to develop server software. -Computers had become enormously quicker since languages such as -C, C++ and Java were first developed but the act of programming had not -itself advanced nearly as much. -Also, it was clear that multiprocessors were becoming universal but -most languages offered little help to program them efficiently -and safely. -

- -

-We decided to take a step back and think about what major issues were -going to dominate software engineering in the years ahead as technology -developed, and how a new language might help address them. -For instance, the rise of multicore CPUs argued that a language should -provide first-class support for some sort of concurrency or parallelism. -And to make resource management tractable in a large concurrent program, -garbage collection, or at least some sort of safe automatic memory management was required. -

- -

-These considerations led to -a -series of discussions from which Go arose, first as a set of ideas and -desiderata, then as a language. -An overarching goal was that Go do more to help the working programmer -by enabling tooling, automating mundane tasks such as code formatting, -and removing obstacles to working on large code bases. -

- -

-A much more expansive description of the goals of Go and how -they are met, or at least approached, is available in the article, -Go at Google: -Language Design in the Service of Software Engineering. -

- -

-What is the history of the project?

-

-Robert Griesemer, Rob Pike and Ken Thompson started sketching the -goals for a new language on the white board on September 21, 2007. -Within a few days the goals had settled into a plan to do something -and a fair idea of what it would be. Design continued part-time in -parallel with unrelated work. By January 2008, Ken had started work -on a compiler with which to explore ideas; it generated C code as its -output. By mid-year the language had become a full-time project and -had settled enough to attempt a production compiler. In May 2008, -Ian Taylor independently started on a GCC front end for Go using the -draft specification. Russ Cox joined in late 2008 and helped move the language -and libraries from prototype to reality. -

- -

-Go became a public open source project on November 10, 2009. -Countless people from the community have contributed ideas, discussions, and code. -

- -

-There are now millions of Go programmers—gophers—around the world, -and there are more every day. -Go's success has far exceeded our expectations. -

- -

-What's the origin of the gopher mascot?

- -

-The mascot and logo were designed by -Renée French, who also designed -Glenda, -the Plan 9 bunny. -A blog post -about the gopher explains how it was -derived from one she used for a WFMU -T-shirt design some years ago. -The logo and mascot are covered by the -Creative Commons Attribution 3.0 -license. -

- -

-The gopher has a -model sheet -illustrating his characteristics and how to represent them correctly. -The model sheet was first shown in a -talk -by Renée at Gophercon in 2016. -He has unique features; he's the Go gopher, not just any old gopher. -

- -

-Is the language called Go or Golang?

- -

-The language is called Go. -The "golang" moniker arose because the web site is -golang.org, not -go.org, which was not available to us. -Many use the golang name, though, and it is handy as -a label. -For instance, the Twitter tag for the language is "#golang". -The language's name is just plain Go, regardless. -

- -

-A side note: Although the -official logo -has two capital letters, the language name is written Go, not GO. -

- -

-Why did you create a new language?

- -

-Go was born out of frustration with existing languages and -environments for the work we were doing at Google. -Programming had become too -difficult and the choice of languages was partly to blame. One had to -choose either efficient compilation, efficient execution, or ease of -programming; all three were not available in the same mainstream -language. Programmers who could were choosing ease over -safety and efficiency by moving to dynamically typed languages such as -Python and JavaScript rather than C++ or, to a lesser extent, Java. -

- -

-We were not alone in our concerns. -After many years with a pretty quiet landscape for programming languages, -Go was among the first of several new languages—Rust, -Elixir, Swift, and more—that have made programming language development -an active, almost mainstream field again. -

- -

-Go addressed these issues by attempting to combine the ease of programming of an interpreted, -dynamically typed -language with the efficiency and safety of a statically typed, compiled language. -It also aimed to be modern, with support for networked and multicore -computing. Finally, working with Go is intended to be fast: it should take -at most a few seconds to build a large executable on a single computer. -To meet these goals required addressing a number of -linguistic issues: an expressive but lightweight type system; -concurrency and garbage collection; rigid dependency specification; -and so on. These cannot be addressed well by libraries or tools; a new -language was called for. -

- -

-The article Go at Google -discusses the background and motivation behind the design of the Go language, -as well as providing more detail about many of the answers presented in this FAQ. -

- - -

-What are Go's ancestors?

-

-Go is mostly in the C family (basic syntax), -with significant input from the Pascal/Modula/Oberon -family (declarations, packages), -plus some ideas from languages -inspired by Tony Hoare's CSP, -such as Newsqueak and Limbo (concurrency). -However, it is a new language across the board. -In every respect the language was designed by thinking -about what programmers do and how to make programming, at least the -kind of programming we do, more effective, which means more fun. -

- -

-What are the guiding principles in the design?

- -

-When Go was designed, Java and C++ were the most commonly -used languages for writing servers, at least at Google. -We felt that these languages required -too much bookkeeping and repetition. -Some programmers reacted by moving towards more dynamic, -fluid languages like Python, at the cost of efficiency and -type safety. -We felt it should be possible to have the efficiency, -the safety, and the fluidity in a single language. -

- -

-Go attempts to reduce the amount of typing in both senses of the word. -Throughout its design, we have tried to reduce clutter and -complexity. There are no forward declarations and no header files; -everything is declared exactly once. Initialization is expressive, -automatic, and easy to use. Syntax is clean and light on keywords. -Stuttering (foo.Foo* myFoo = new(foo.Foo)) is reduced by -simple type derivation using the := -declare-and-initialize construct. And perhaps most radically, there -is no type hierarchy: types just are, they don't have to -announce their relationships. These simplifications allow Go to be -expressive yet comprehensible without sacrificing, well, sophistication. -

-

-Another important principle is to keep the concepts orthogonal. -Methods can be implemented for any type; structures represent data while -interfaces represent abstraction; and so on. Orthogonality makes it -easier to understand what happens when things combine. -

- -

Usage

- -

-Is Google using Go internally?

- -

-Yes. Go is used widely in production inside Google. -One easy example is the server behind -golang.org. -It's just the godoc -document server running in a production configuration on -Google App Engine. -

- -

-A more significant instance is Google's download server, dl.google.com, -which delivers Chrome binaries and other large installables such as apt-get -packages. -

- -

-Go is not the only language used at Google, far from it, but it is a key language -for a number of areas including -site reliability -engineering (SRE) -and large-scale data processing. -

- -

-What other companies use Go?

- -

-Go usage is growing worldwide, especially but by no means exclusively -in the cloud computing space. -A couple of major cloud infrastructure projects written in Go are -Docker and Kubernetes, -but there are many more. -

- -

-It's not just cloud, though. -The Go Wiki includes a -page, -updated regularly, that lists some of the many companies using Go. -

- -

-The Wiki also has a page with links to -success stories -about companies and projects that are using the language. -

- - - -

-It is possible to use C and Go together in the same address space, -but it is not a natural fit and can require special interface software. -Also, linking C with Go code gives up the memory -safety and stack management properties that Go provides. -Sometimes it's absolutely necessary to use C libraries to solve a problem, -but doing so always introduces an element of risk not present with -pure Go code, so do so with care. -

- -

-If you do need to use C with Go, how to proceed depends on the Go -compiler implementation. -There are three Go compiler implementations supported by the -Go team. -These are gc, the default compiler, -gccgo, which uses the GCC back end, -and a somewhat less mature gollvm, which uses the LLVM infrastructure. -

- -

-Gc uses a different calling convention and linker from C and -therefore cannot be called directly from C programs, or vice versa. -The cgo program provides the mechanism for a -“foreign function interface” to allow safe calling of -C libraries from Go code. -SWIG extends this capability to C++ libraries. -

- -

-You can also use cgo and SWIG with Gccgo and gollvm. -Since they use a traditional API, it's also possible, with great care, -to link code from these compilers directly with GCC/LLVM-compiled C or C++ programs. -However, doing so safely requires an understanding of the calling conventions for -all languages concerned, as well as concern for stack limits when calling C or C++ -from Go. -

- -

-What IDEs does Go support?

- -

-The Go project does not include a custom IDE, but the language and -libraries have been designed to make it easy to analyze source code. -As a consequence, most well-known editors and IDEs support Go well, -either directly or through a plugin. -

- -

-The list of well-known IDEs and editors that have good Go support -available includes Emacs, Vim, VSCode, Atom, Eclipse, Sublime, IntelliJ -(through a custom variant called Goland), and many more. -Chances are your favorite environment is a productive one for -programming in Go. -

- -

-Does Go support Google's protocol buffers?

- -

-A separate open source project provides the necessary compiler plugin and library. -It is available at -github.com/golang/protobuf/. -

- - -

-Can I translate the Go home page into another language?

- -

-Absolutely. We encourage developers to make Go Language sites in their own languages. -However, if you choose to add the Google logo or branding to your site -(it does not appear on golang.org), -you will need to abide by the guidelines at -www.google.com/permissions/guidelines.html -

- -

Design

- -

-Does Go have a runtime?

- -

-Go does have an extensive library, called the runtime, -that is part of every Go program. -The runtime library implements garbage collection, concurrency, -stack management, and other critical features of the Go language. -Although it is more central to the language, Go's runtime is analogous -to libc, the C library. -

- -

-It is important to understand, however, that Go's runtime does not -include a virtual machine, such as is provided by the Java runtime. -Go programs are compiled ahead of time to native machine code -(or JavaScript or WebAssembly, for some variant implementations). -Thus, although the term is often used to describe the virtual -environment in which a program runs, in Go the word “runtime” -is just the name given to the library providing critical language services. -

- -

-What's up with Unicode identifiers?

- -

-When designing Go, we wanted to make sure that it was not -overly ASCII-centric, -which meant extending the space of identifiers from the -confines of 7-bit ASCII. -Go's rule—identifier characters must be -letters or digits as defined by Unicode—is simple to understand -and to implement but has restrictions. -Combining characters are -excluded by design, for instance, -and that excludes some languages such as Devanagari. -

- -

-This rule has one other unfortunate consequence. -Since an exported identifier must begin with an -upper-case letter, identifiers created from characters -in some languages can, by definition, not be exported. -For now the -only solution is to use something like X日本語, which -is clearly unsatisfactory. -

- -

-Since the earliest version of the language, there has been considerable -thought into how best to expand the identifier space to accommodate -programmers using other native languages. -Exactly what to do remains an active topic of discussion, and a future -version of the language may be more liberal in its definition -of an identifier. -For instance, it might adopt some of the ideas from the Unicode -organization's recommendations -for identifiers. -Whatever happens, it must be done compatibly while preserving -(or perhaps expanding) the way letter case determines visibility of -identifiers, which remains one of our favorite features of Go. -

- -

-For the time being, we have a simple rule that can be expanded later -without breaking programs, one that avoids bugs that would surely arise -from a rule that admits ambiguous identifiers. -

- -

Why does Go not have feature X?

- -

-Every language contains novel features and omits someone's favorite -feature. Go was designed with an eye on felicity of programming, speed of -compilation, orthogonality of concepts, and the need to support features -such as concurrency and garbage collection. Your favorite feature may be -missing because it doesn't fit, because it affects compilation speed or -clarity of design, or because it would make the fundamental system model -too difficult. -

- -

-If it bothers you that Go is missing feature X, -please forgive us and investigate the features that Go does have. You might find that -they compensate in interesting ways for the lack of X. -

- -

-Why does Go not have generic types?

-

-A language proposal -implementing a form of generic types has been accepted for -inclusion in the language. -If all goes well it will be available in the Go 1.18 release. -

- -

-Go was intended as a language for writing server programs that would be -easy to maintain over time. -(See this -article for more background.) -The design concentrated on things like scalability, readability, and -concurrency. -Polymorphic programming did not seem essential to the language's -goals at the time, and so was left out for simplicity. -

- -

-The language is more mature now, and there is scope to consider -some form of generic programming. -However, there remain some caveats. -

- -

-Generics are convenient but they come at a cost in -complexity in the type system and run-time. We haven't yet found a -design that gives value proportionate to the complexity, although we -continue to think about it. Meanwhile, Go's built-in maps and slices, -plus the ability to use the empty interface to construct containers -(with explicit unboxing) mean in many cases it is possible to write -code that does what generics would enable, if less smoothly. -

- -

-The topic remains open. -For a look at several previous unsuccessful attempts to -design a good generics solution for Go, see -this proposal. -

- -

-Why does Go not have exceptions?

-

-We believe that coupling exceptions to a control -structure, as in the try-catch-finally idiom, results in -convoluted code. It also tends to encourage programmers to label -too many ordinary errors, such as failing to open a file, as -exceptional. -

- -

-Go takes a different approach. For plain error handling, Go's multi-value -returns make it easy to report an error without overloading the return value. -A canonical error type, coupled -with Go's other features, makes error handling pleasant but quite different -from that in other languages. -

- -

-Go also has a couple -of built-in functions to signal and recover from truly exceptional -conditions. The recovery mechanism is executed only as part of a -function's state being torn down after an error, which is sufficient -to handle catastrophe but requires no extra control structures and, -when used well, can result in clean error-handling code. -

- -

-See the Defer, Panic, and Recover article for details. -Also, the Errors are values blog post -describes one approach to handling errors cleanly in Go by demonstrating that, -since errors are just values, the full power of Go can be deployed in error handling. -

- -

-Why does Go not have assertions?

- -

-Go doesn't provide assertions. They are undeniably convenient, but our -experience has been that programmers use them as a crutch to avoid thinking -about proper error handling and reporting. Proper error handling means that -servers continue to operate instead of crashing after a non-fatal error. -Proper error reporting means that errors are direct and to the point, -saving the programmer from interpreting a large crash trace. Precise -errors are particularly important when the programmer seeing the errors is -not familiar with the code. -

- -

-We understand that this is a point of contention. There are many things in -the Go language and libraries that differ from modern practices, simply -because we feel it's sometimes worth trying a different approach. -

- -

-Why build concurrency on the ideas of CSP?

-

-Concurrency and multi-threaded programming have over time -developed a reputation for difficulty. We believe this is due partly to complex -designs such as -pthreads -and partly to overemphasis on low-level details -such as mutexes, condition variables, and memory barriers. -Higher-level interfaces enable much simpler code, even if there are still -mutexes and such under the covers. -

- -

-One of the most successful models for providing high-level linguistic support -for concurrency comes from Hoare's Communicating Sequential Processes, or CSP. -Occam and Erlang are two well known languages that stem from CSP. -Go's concurrency primitives derive from a different part of the family tree -whose main contribution is the powerful notion of channels as first class objects. -Experience with several earlier languages has shown that the CSP model -fits well into a procedural language framework. -

- -

-Why goroutines instead of threads?

-

-Goroutines are part of making concurrency easy to use. The idea, which has -been around for a while, is to multiplex independently executing -functions—coroutines—onto a set of threads. -When a coroutine blocks, such as by calling a blocking system call, -the run-time automatically moves other coroutines on the same operating -system thread to a different, runnable thread so they won't be blocked. -The programmer sees none of this, which is the point. -The result, which we call goroutines, can be very cheap: they have little -overhead beyond the memory for the stack, which is just a few kilobytes. -

- -

-To make the stacks small, Go's run-time uses resizable, bounded stacks. A newly -minted goroutine is given a few kilobytes, which is almost always enough. -When it isn't, the run-time grows (and shrinks) the memory for storing -the stack automatically, allowing many goroutines to live in a modest -amount of memory. -The CPU overhead averages about three cheap instructions per function call. -It is practical to create hundreds of thousands of goroutines in the same -address space. -If goroutines were just threads, system resources would -run out at a much smaller number. -

- -

-Why are map operations not defined to be atomic?

- -

-After long discussion it was decided that the typical use of maps did not require -safe access from multiple goroutines, and in those cases where it did, the map was -probably part of some larger data structure or computation that was already -synchronized. Therefore requiring that all map operations grab a mutex would slow -down most programs and add safety to few. This was not an easy decision, -however, since it means uncontrolled map access can crash the program. -

- -

-The language does not preclude atomic map updates. When required, such -as when hosting an untrusted program, the implementation could interlock -map access. -

- -

-Map access is unsafe only when updates are occurring. -As long as all goroutines are only reading—looking up elements in the map, -including iterating through it using a -for range loop—and not changing the map -by assigning to elements or doing deletions, -it is safe for them to access the map concurrently without synchronization. -

- -

-As an aid to correct map use, some implementations of the language -contain a special check that automatically reports at run time when a map is modified -unsafely by concurrent execution. -

- -

-Will you accept my language change?

- -

-People often suggest improvements to the language—the -mailing list -contains a rich history of such discussions—but very few of these changes have -been accepted. -

- -

-Although Go is an open source project, the language and libraries are protected -by a compatibility promise that prevents -changes that break existing programs, at least at the source code level -(programs may need to be recompiled occasionally to stay current). -If your proposal violates the Go 1 specification we cannot even entertain the -idea, regardless of its merit. -A future major release of Go may be incompatible with Go 1, but discussions -on that topic have only just begun and one thing is certain: -there will be very few such incompatibilities introduced in the process. -Moreover, the compatibility promise encourages us to provide an automatic path -forward for old programs to adapt should that situation arise. -

- -

-Even if your proposal is compatible with the Go 1 spec, it might -not be in the spirit of Go's design goals. -The article Go -at Google: Language Design in the Service of Software Engineering -explains Go's origins and the motivation behind its design. -

- -

Types

- -

-Is Go an object-oriented language?

- -

-Yes and no. Although Go has types and methods and allows an -object-oriented style of programming, there is no type hierarchy. -The concept of “interface” in Go provides a different approach that -we believe is easy to use and in some ways more general. There are -also ways to embed types in other types to provide something -analogous—but not identical—to subclassing. -Moreover, methods in Go are more general than in C++ or Java: -they can be defined for any sort of data, even built-in types such -as plain, “unboxed” integers. -They are not restricted to structs (classes). -

- -

-Also, the lack of a type hierarchy makes “objects” in Go feel much more -lightweight than in languages such as C++ or Java. -

- -

-How do I get dynamic dispatch of methods?

- -

-The only way to have dynamically dispatched methods is through an -interface. Methods on a struct or any other concrete type are always resolved statically. -

- -

-Why is there no type inheritance?

-

-Object-oriented programming, at least in the best-known languages, -involves too much discussion of the relationships between types, -relationships that often could be derived automatically. Go takes a -different approach. -

- -

-Rather than requiring the programmer to declare ahead of time that two -types are related, in Go a type automatically satisfies any interface -that specifies a subset of its methods. Besides reducing the -bookkeeping, this approach has real advantages. Types can satisfy -many interfaces at once, without the complexities of traditional -multiple inheritance. -Interfaces can be very lightweight—an interface with -one or even zero methods can express a useful concept. -Interfaces can be added after the fact if a new idea comes along -or for testing—without annotating the original types. -Because there are no explicit relationships between types -and interfaces, there is no type hierarchy to manage or discuss. -

- -

-It's possible to use these ideas to construct something analogous to -type-safe Unix pipes. For instance, see how fmt.Fprintf -enables formatted printing to any output, not just a file, or how the -bufio package can be completely separate from file I/O, -or how the image packages generate compressed -image files. All these ideas stem from a single interface -(io.Writer) representing a single method -(Write). And that's only scratching the surface. -Go's interfaces have a profound influence on how programs are structured. -

- -

-It takes some getting used to but this implicit style of type -dependency is one of the most productive things about Go. -

- -

-Why is len a function and not a method?

-

-We debated this issue but decided -implementing len and friends as functions was fine in practice and -didn't complicate questions about the interface (in the Go type sense) -of basic types. -

- -

-Why does Go not support overloading of methods and operators?

-

-Method dispatch is simplified if it doesn't need to do type matching as well. -Experience with other languages told us that having a variety of -methods with the same name but different signatures was occasionally useful -but that it could also be confusing and fragile in practice. Matching only by name -and requiring consistency in the types was a major simplifying decision -in Go's type system. -

- -

-Regarding operator overloading, it seems more a convenience than an absolute -requirement. Again, things are simpler without it. -

- -

-Why doesn't Go have "implements" declarations?

- -

-A Go type satisfies an interface by implementing the methods of that interface, -nothing more. This property allows interfaces to be defined and used without -needing to modify existing code. It enables a kind of -structural typing that -promotes separation of concerns and improves code re-use, and makes it easier -to build on patterns that emerge as the code develops. -The semantics of interfaces is one of the main reasons for Go's nimble, -lightweight feel. -

- -

-See the question on type inheritance for more detail. -

- -

-How can I guarantee my type satisfies an interface?

- -

-You can ask the compiler to check that the type T implements the -interface I by attempting an assignment using the zero value for -T or pointer to T, as appropriate: -

- -
-type T struct{}
-var _ I = T{}       // Verify that T implements I.
-var _ I = (*T)(nil) // Verify that *T implements I.
-
- -

-If T (or *T, accordingly) doesn't implement -I, the mistake will be caught at compile time. -

- -

-If you wish the users of an interface to explicitly declare that they implement -it, you can add a method with a descriptive name to the interface's method set. -For example: -

- -
-type Fooer interface {
-    Foo()
-    ImplementsFooer()
-}
-
- -

-A type must then implement the ImplementsFooer method to be a -Fooer, clearly documenting the fact and announcing it in -go doc's output. -

- -
-type Bar struct{}
-func (b Bar) ImplementsFooer() {}
-func (b Bar) Foo() {}
-
- -

-Most code doesn't make use of such constraints, since they limit the utility of -the interface idea. Sometimes, though, they're necessary to resolve ambiguities -among similar interfaces. -

- -

-Why doesn't type T satisfy the Equal interface?

- -

-Consider this simple interface to represent an object that can compare -itself with another value: -

- -
-type Equaler interface {
-    Equal(Equaler) bool
-}
-
- -

-and this type, T: -

- -
-type T int
-func (t T) Equal(u T) bool { return t == u } // does not satisfy Equaler
-
- -

-Unlike the analogous situation in some polymorphic type systems, -T does not implement Equaler. -The argument type of T.Equal is T, -not literally the required type Equaler. -

- -

-In Go, the type system does not promote the argument of -Equal; that is the programmer's responsibility, as -illustrated by the type T2, which does implement -Equaler: -

- -
-type T2 int
-func (t T2) Equal(u Equaler) bool { return t == u.(T2) }  // satisfies Equaler
-
- -

-Even this isn't like other type systems, though, because in Go any -type that satisfies Equaler could be passed as the -argument to T2.Equal, and at run time we must -check that the argument is of type T2. -Some languages arrange to make that guarantee at compile time. -

- -

-A related example goes the other way: -

- -
-type Opener interface {
-   Open() Reader
-}
-
-func (t T3) Open() *os.File
-
- -

-In Go, T3 does not satisfy Opener, -although it might in another language. -

- -

-While it is true that Go's type system does less for the programmer -in such cases, the lack of subtyping makes the rules about -interface satisfaction very easy to state: are the function's names -and signatures exactly those of the interface? -Go's rule is also easy to implement efficiently. -We feel these benefits offset the lack of -automatic type promotion. Should Go one day adopt some form of polymorphic -typing, we expect there would be a way to express the idea of these -examples and also have them be statically checked. -

- -

-Can I convert a []T to an []interface{}?

- -

-Not directly. -It is disallowed by the language specification because the two types -do not have the same representation in memory. -It is necessary to copy the elements individually to the destination -slice. This example converts a slice of int to a slice of -interface{}: -

- -
-t := []int{1, 2, 3, 4}
-s := make([]interface{}, len(t))
-for i, v := range t {
-    s[i] = v
-}
-
- -

-Can I convert []T1 to []T2 if T1 and T2 have the same underlying type?

- -This last line of this code sample does not compile. - -
-type T1 int
-type T2 int
-var t1 T1
-var x = T2(t1) // OK
-var st1 []T1
-var sx = ([]T2)(st1) // NOT OK
-
- -

-In Go, types are closely tied to methods, in that every named type has -a (possibly empty) method set. -The general rule is that you can change the name of the type being -converted (and thus possibly change its method set) but you can't -change the name (and method set) of elements of a composite type. -Go requires you to be explicit about type conversions. -

- -

-Why is my nil error value not equal to nil? -

- -

-Under the covers, interfaces are implemented as two elements, a type T -and a value V. -V is a concrete value such as an int, -struct or pointer, never an interface itself, and has -type T. -For instance, if we store the int value 3 in an interface, -the resulting interface value has, schematically, -(T=int, V=3). -The value V is also known as the interface's -dynamic value, -since a given interface variable might hold different values V -(and corresponding types T) -during the execution of the program. -

- -

-An interface value is nil only if the V and T -are both unset, (T=nil, V is not set), -In particular, a nil interface will always hold a nil type. -If we store a nil pointer of type *int inside -an interface value, the inner type will be *int regardless of the value of the pointer: -(T=*int, V=nil). -Such an interface value will therefore be non-nil -even when the pointer value V inside is nil. -

- -

-This situation can be confusing, and arises when a nil value is -stored inside an interface value such as an error return: -

- -
-func returnsError() error {
-	var p *MyError = nil
-	if bad() {
-		p = ErrBad
-	}
-	return p // Will always return a non-nil error.
-}
-
- -

-If all goes well, the function returns a nil p, -so the return value is an error interface -value holding (T=*MyError, V=nil). -This means that if the caller compares the returned error to nil, -it will always look as if there was an error even if nothing bad happened. -To return a proper nil error to the caller, -the function must return an explicit nil: -

- - -
-func returnsError() error {
-	if bad() {
-		return ErrBad
-	}
-	return nil
-}
-
- -

-It's a good idea for functions -that return errors always to use the error type in -their signature (as we did above) rather than a concrete type such -as *MyError, to help guarantee the error is -created correctly. As an example, -os.Open -returns an error even though, if not nil, -it's always of concrete type -*os.PathError. -

- -

-Similar situations to those described here can arise whenever interfaces are used. -Just keep in mind that if any concrete value -has been stored in the interface, the interface will not be nil. -For more information, see -The Laws of Reflection. -

- - -

-Why are there no untagged unions, as in C?

- -

-Untagged unions would violate Go's memory safety -guarantees. -

- -

-Why does Go not have variant types?

- -

-Variant types, also known as algebraic types, provide a way to specify -that a value might take one of a set of other types, but only those -types. A common example in systems programming would specify that an -error is, say, a network error, a security error or an application -error and allow the caller to discriminate the source of the problem -by examining the type of the error. Another example is a syntax tree -in which each node can be a different type: declaration, statement, -assignment and so on. -

- -

-We considered adding variant types to Go, but after discussion -decided to leave them out because they overlap in confusing ways -with interfaces. What would happen if the elements of a variant type -were themselves interfaces? -

- -

-Also, some of what variant types address is already covered by the -language. The error example is easy to express using an interface -value to hold the error and a type switch to discriminate cases. The -syntax tree example is also doable, although not as elegantly. -

- -

-Why does Go not have covariant result types?

- -

-Covariant result types would mean that an interface like -

- -
-type Copyable interface {
-	Copy() interface{}
-}
-
- -

-would be satisfied by the method -

- -
-func (v Value) Copy() Value
-
- -

because Value implements the empty interface. -In Go method types must match exactly, so Value does not -implement Copyable. -Go separates the notion of what a -type does—its methods—from the type's implementation. -If two methods return different types, they are not doing the same thing. -Programmers who want covariant result types are often trying to -express a type hierarchy through interfaces. -In Go it's more natural to have a clean separation between interface -and implementation. -

- -

Values

- -

-Why does Go not provide implicit numeric conversions?

- -

-The convenience of automatic conversion between numeric types in C is -outweighed by the confusion it causes. When is an expression unsigned? -How big is the value? Does it overflow? Is the result portable, independent -of the machine on which it executes? -It also complicates the compiler; “the usual arithmetic conversions” -are not easy to implement and inconsistent across architectures. -For reasons of portability, we decided to make things clear and straightforward -at the cost of some explicit conversions in the code. -The definition of constants in Go—arbitrary precision values free -of signedness and size annotations—ameliorates matters considerably, -though. -

- -

-A related detail is that, unlike in C, int and int64 -are distinct types even if int is a 64-bit type. The int -type is generic; if you care about how many bits an integer holds, Go -encourages you to be explicit. -

- -

-How do constants work in Go?

- -

-Although Go is strict about conversion between variables of different -numeric types, constants in the language are much more flexible. -Literal constants such as 23, 3.14159 -and math.Pi -occupy a sort of ideal number space, with arbitrary precision and -no overflow or underflow. -For instance, the value of math.Pi is specified to 63 places -in the source code, and constant expressions involving the value keep -precision beyond what a float64 could hold. -Only when the constant or constant expression is assigned to a -variable—a memory location in the program—does -it become a "computer" number with -the usual floating-point properties and precision. -

- -

-Also, -because they are just numbers, not typed values, constants in Go can be -used more freely than variables, thereby softening some of the awkwardness -around the strict conversion rules. -One can write expressions such as -

- -
-sqrt2 := math.Sqrt(2)
-
- -

-without complaint from the compiler because the ideal number 2 -can be converted safely and accurately -to a float64 for the call to math.Sqrt. -

- -

-A blog post titled Constants -explores this topic in more detail. -

- -

-Why are maps built in?

-

-The same reason strings are: they are such a powerful and important data -structure that providing one excellent implementation with syntactic support -makes programming more pleasant. We believe that Go's implementation of maps -is strong enough that it will serve for the vast majority of uses. -If a specific application can benefit from a custom implementation, it's possible -to write one but it will not be as convenient syntactically; this seems a reasonable tradeoff. -

- -

-Why don't maps allow slices as keys?

-

-Map lookup requires an equality operator, which slices do not implement. -They don't implement equality because equality is not well defined on such types; -there are multiple considerations involving shallow vs. deep comparison, pointer vs. -value comparison, how to deal with recursive types, and so on. -We may revisit this issue—and implementing equality for slices -will not invalidate any existing programs—but without a clear idea of what -equality of slices should mean, it was simpler to leave it out for now. -

- -

-In Go 1, unlike prior releases, equality is defined for structs and arrays, so such -types can be used as map keys. Slices still do not have a definition of equality, though. -

- -

-Why are maps, slices, and channels references while arrays are values?

-

-There's a lot of history on that topic. Early on, maps and channels -were syntactically pointers and it was impossible to declare or use a -non-pointer instance. Also, we struggled with how arrays should work. -Eventually we decided that the strict separation of pointers and -values made the language harder to use. Changing these -types to act as references to the associated, shared data structures resolved -these issues. This change added some regrettable complexity to the -language but had a large effect on usability: Go became a more -productive, comfortable language when it was introduced. -

- -

Writing Code

- -

-How are libraries documented?

- -

-There is a program, godoc, written in Go, that extracts -package documentation from the source code and serves it as a web -page with links to declarations, files, and so on. -An instance is running at -golang.org/pkg/. -In fact, godoc implements the full site at -golang.org/. -

- -

-A godoc instance may be configured to provide rich, -interactive static analyses of symbols in the programs it displays; details are -listed here. -

- -

-For access to documentation from the command line, the -go tool has a -doc -subcommand that provides a textual interface to the same information. -

- -

-Is there a Go programming style guide?

- -

-There is no explicit style guide, although there is certainly -a recognizable "Go style". -

- -

-Go has established conventions to guide decisions around -naming, layout, and file organization. -The document Effective Go -contains some advice on these topics. -More directly, the program gofmt is a pretty-printer -whose purpose is to enforce layout rules; it replaces the usual -compendium of do's and don'ts that allows interpretation. -All the Go code in the repository, and the vast majority in the -open source world, has been run through gofmt. -

- -

-The document titled -Go Code Review Comments -is a collection of very short essays about details of Go idiom that are often -missed by programmers. -It is a handy reference for people doing code reviews for Go projects. -

- -

-How do I submit patches to the Go libraries?

- -

-The library sources are in the src directory of the repository. -If you want to make a significant change, please discuss on the mailing list before embarking. -

- -

-See the document -Contributing to the Go project -for more information about how to proceed. -

- -

-Why does "go get" use HTTPS when cloning a repository?

- -

-Companies often permit outgoing traffic only on the standard TCP ports 80 (HTTP) -and 443 (HTTPS), blocking outgoing traffic on other ports, including TCP port 9418 -(git) and TCP port 22 (SSH). -When using HTTPS instead of HTTP, git enforces certificate validation by -default, providing protection against man-in-the-middle, eavesdropping and tampering attacks. -The go get command therefore uses HTTPS for safety. -

- -

-Git can be configured to authenticate over HTTPS or to use SSH in place of HTTPS. -To authenticate over HTTPS, you can add a line -to the $HOME/.netrc file that git consults: -

-
-machine github.com login USERNAME password APIKEY
-
-

-For GitHub accounts, the password can be a -personal access token. -

- -

-Git can also be configured to use SSH in place of HTTPS for URLs matching a given prefix. -For example, to use SSH for all GitHub access, -add these lines to your ~/.gitconfig: -

-
-[url "ssh://git@github.com/"]
-	insteadOf = https://github.com/
-
- -

-How should I manage package versions using "go get"?

- -

-Since the inception of the project, Go has had no explicit concept of package versions, -but that is changing. -Versioning is a source of significant complexity, especially in large code bases, -and it has taken some time to develop an -approach that works well at scale in a large enough -variety of situations to be appropriate to supply to all Go users. -

- -

-The Go 1.11 release adds new, experimental support -for package versioning to the go command, -in the form of Go modules. -For more information, see the Go 1.11 release notes -and the go command documentation. -

- -

-Regardless of the actual package management technology, -"go get" and the larger Go toolchain does provide isolation of -packages with different import paths. -For example, the standard library's html/template and text/template -coexist even though both are "package template". -This observation leads to some advice for package authors and package users. -

- -

-Packages intended for public use should try to maintain backwards compatibility as they evolve. -The Go 1 compatibility guidelines are a good reference here: -don't remove exported names, encourage tagged composite literals, and so on. -If different functionality is required, add a new name instead of changing an old one. -If a complete break is required, create a new package with a new import path. -

- -

-If you're using an externally supplied package and worry that it might change in -unexpected ways, but are not yet using Go modules, -the simplest solution is to copy it to your local repository. -This is the approach Google takes internally and is supported by the -go command through a technique called "vendoring". -This involves -storing a copy of the dependency under a new import path that identifies it as a local copy. -See the design -document for details. -

- -

Pointers and Allocation

- -

-When are function parameters passed by value?

- -

-As in all languages in the C family, everything in Go is passed by value. -That is, a function always gets a copy of the -thing being passed, as if there were an assignment statement assigning the -value to the parameter. For instance, passing an int value -to a function makes a copy of the int, and passing a pointer -value makes a copy of the pointer, but not the data it points to. -(See a later -section for a discussion of how this affects method receivers.) -

- -

-Map and slice values behave like pointers: they are descriptors that -contain pointers to the underlying map or slice data. Copying a map or -slice value doesn't copy the data it points to. Copying an interface value -makes a copy of the thing stored in the interface value. If the interface -value holds a struct, copying the interface value makes a copy of the -struct. If the interface value holds a pointer, copying the interface value -makes a copy of the pointer, but again not the data it points to. -

- -

-Note that this discussion is about the semantics of the operations. -Actual implementations may apply optimizations to avoid copying -as long as the optimizations do not change the semantics. -

- -

-When should I use a pointer to an interface?

- -

-Almost never. Pointers to interface values arise only in rare, tricky situations involving -disguising an interface value's type for delayed evaluation. -

- -

-It is a common mistake to pass a pointer to an interface value -to a function expecting an interface. The compiler will complain about this -error but the situation can still be confusing, because sometimes a -pointer -is necessary to satisfy an interface. -The insight is that although a pointer to a concrete type can satisfy -an interface, with one exception a pointer to an interface can never satisfy an interface. -

- -

-Consider the variable declaration, -

- -
-var w io.Writer
-
- -

-The printing function fmt.Fprintf takes as its first argument -a value that satisfies io.Writer—something that implements -the canonical Write method. Thus we can write -

- -
-fmt.Fprintf(w, "hello, world\n")
-
- -

-If however we pass the address of w, the program will not compile. -

- -
-fmt.Fprintf(&w, "hello, world\n") // Compile-time error.
-
- -

-The one exception is that any value, even a pointer to an interface, can be assigned to -a variable of empty interface type (interface{}). -Even so, it's almost certainly a mistake if the value is a pointer to an interface; -the result can be confusing. -

- -

-Should I define methods on values or pointers?

- -
-func (s *MyStruct) pointerMethod() { } // method on pointer
-func (s MyStruct)  valueMethod()   { } // method on value
-
- -

-For programmers unaccustomed to pointers, the distinction between these -two examples can be confusing, but the situation is actually very simple. -When defining a method on a type, the receiver (s in the above -examples) behaves exactly as if it were an argument to the method. -Whether to define the receiver as a value or as a pointer is the same -question, then, as whether a function argument should be a value or -a pointer. -There are several considerations. -

- -

-First, and most important, does the method need to modify the -receiver? -If it does, the receiver must be a pointer. -(Slices and maps act as references, so their story is a little -more subtle, but for instance to change the length of a slice -in a method the receiver must still be a pointer.) -In the examples above, if pointerMethod modifies -the fields of s, -the caller will see those changes, but valueMethod -is called with a copy of the caller's argument (that's the definition -of passing a value), so changes it makes will be invisible to the caller. -

- -

-By the way, in Java method receivers are always pointers, -although their pointer nature is somewhat disguised -(and there is a proposal to add value receivers to the language). -It is the value receivers in Go that are unusual. -

- -

-Second is the consideration of efficiency. If the receiver is large, -a big struct for instance, it will be much cheaper to -use a pointer receiver. -

- -

-Next is consistency. If some of the methods of the type must have -pointer receivers, the rest should too, so the method set is -consistent regardless of how the type is used. -See the section on method sets -for details. -

- -

-For types such as basic types, slices, and small structs, -a value receiver is very cheap so unless the semantics of the method -requires a pointer, a value receiver is efficient and clear. -

- - -

-What's the difference between new and make?

- -

-In short: new allocates memory, while make initializes -the slice, map, and channel types. -

- -

-See the relevant section -of Effective Go for more details. -

- -

-What is the size of an int on a 64 bit machine?

- -

-The sizes of int and uint are implementation-specific -but the same as each other on a given platform. -For portability, code that relies on a particular -size of value should use an explicitly sized type, like int64. -On 32-bit machines the compilers use 32-bit integers by default, -while on 64-bit machines integers have 64 bits. -(Historically, this was not always true.) -

- -

-On the other hand, floating-point scalars and complex -types are always sized (there are no float or complex basic types), -because programmers should be aware of precision when using floating-point numbers. -The default type used for an (untyped) floating-point constant is float64. -Thus foo := 3.0 declares a variable foo -of type float64. -For a float32 variable initialized by an (untyped) constant, the variable type -must be specified explicitly in the variable declaration: -

- -
-var foo float32 = 3.0
-
- -

-Alternatively, the constant must be given a type with a conversion as in -foo := float32(3.0). -

- -

-How do I know whether a variable is allocated on the heap or the stack?

- -

-From a correctness standpoint, you don't need to know. -Each variable in Go exists as long as there are references to it. -The storage location chosen by the implementation is irrelevant to the -semantics of the language. -

- -

-The storage location does have an effect on writing efficient programs. -When possible, the Go compilers will allocate variables that are -local to a function in that function's stack frame. However, if the -compiler cannot prove that the variable is not referenced after the -function returns, then the compiler must allocate the variable on the -garbage-collected heap to avoid dangling pointer errors. -Also, if a local variable is very large, it might make more sense -to store it on the heap rather than the stack. -

- -

-In the current compilers, if a variable has its address taken, that variable -is a candidate for allocation on the heap. However, a basic escape -analysis recognizes some cases when such variables will not -live past the return from the function and can reside on the stack. -

- -

-Why does my Go process use so much virtual memory?

- -

-The Go memory allocator reserves a large region of virtual memory as an arena -for allocations. This virtual memory is local to the specific Go process; the -reservation does not deprive other processes of memory. -

- -

-To find the amount of actual memory allocated to a Go process, use the Unix -top command and consult the RES (Linux) or -RSIZE (macOS) columns. - -

- -

Concurrency

- -

-What operations are atomic? What about mutexes?

- -

-A description of the atomicity of operations in Go can be found in -the Go Memory Model document. -

- -

-Low-level synchronization and atomic primitives are available in the -sync and -sync/atomic -packages. -These packages are good for simple tasks such as incrementing -reference counts or guaranteeing small-scale mutual exclusion. -

- -

-For higher-level operations, such as coordination among -concurrent servers, higher-level techniques can lead -to nicer programs, and Go supports this approach through -its goroutines and channels. -For instance, you can structure your program so that only one -goroutine at a time is ever responsible for a particular piece of data. -That approach is summarized by the original -Go proverb, -

- -

-Do not communicate by sharing memory. Instead, share memory by communicating. -

- -

-See the Share Memory By Communicating code walk -and its -associated article for a detailed discussion of this concept. -

- -

-Large concurrent programs are likely to borrow from both these toolkits. -

- -

-Why doesn't my program run faster with more CPUs?

- -

-Whether a program runs faster with more CPUs depends on the problem -it is solving. -The Go language provides concurrency primitives, such as goroutines -and channels, but concurrency only enables parallelism -when the underlying problem is intrinsically parallel. -Problems that are intrinsically sequential cannot be sped up by adding -more CPUs, while those that can be broken into pieces that can -execute in parallel can be sped up, sometimes dramatically. -

- -

-Sometimes adding more CPUs can slow a program down. -In practical terms, programs that spend more time -synchronizing or communicating than doing useful computation -may experience performance degradation when using -multiple OS threads. -This is because passing data between threads involves switching -contexts, which has significant cost, and that cost can increase -with more CPUs. -For instance, the prime sieve example -from the Go specification has no significant parallelism although it launches many -goroutines; increasing the number of threads (CPUs) is more likely to slow it down than -to speed it up. -

- -

-For more detail on this topic see the talk entitled -Concurrency -is not Parallelism. - -

-How can I control the number of CPUs?

- -

-The number of CPUs available simultaneously to executing goroutines is -controlled by the GOMAXPROCS shell environment variable, -whose default value is the number of CPU cores available. -Programs with the potential for parallel execution should therefore -achieve it by default on a multiple-CPU machine. -To change the number of parallel CPUs to use, -set the environment variable or use the similarly-named -function -of the runtime package to configure the -run-time support to utilize a different number of threads. -Setting it to 1 eliminates the possibility of true parallelism, -forcing independent goroutines to take turns executing. -

- -

-The runtime can allocate more threads than the value -of GOMAXPROCS to service multiple outstanding -I/O requests. -GOMAXPROCS only affects how many goroutines -can actually execute at once; arbitrarily more may be blocked -in system calls. -

- -

-Go's goroutine scheduler is not as good as it needs to be, although it -has improved over time. -In the future, it may better optimize its use of OS threads. -For now, if there are performance issues, -setting GOMAXPROCS on a per-application basis may help. -

- - -

-Why is there no goroutine ID?

- -

-Goroutines do not have names; they are just anonymous workers. -They expose no unique identifier, name, or data structure to the programmer. -Some people are surprised by this, expecting the go -statement to return some item that can be used to access and control -the goroutine later. -

- -

-The fundamental reason goroutines are anonymous is so that -the full Go language is available when programming concurrent code. -By contrast, the usage patterns that develop when threads and goroutines are -named can restrict what a library using them can do. -

- -

-Here is an illustration of the difficulties. -Once one names a goroutine and constructs a model around -it, it becomes special, and one is tempted to associate all computation -with that goroutine, ignoring the possibility -of using multiple, possibly shared goroutines for the processing. -If the net/http package associated per-request -state with a goroutine, -clients would be unable to use more goroutines -when serving a request. -

- -

-Moreover, experience with libraries such as those for graphics systems -that require all processing to occur on the "main thread" -has shown how awkward and limiting the approach can be when -deployed in a concurrent language. -The very existence of a special thread or goroutine forces -the programmer to distort the program to avoid crashes -and other problems caused by inadvertently operating -on the wrong thread. -

- -

-For those cases where a particular goroutine is truly special, -the language provides features such as channels that can be -used in flexible ways to interact with it. -

- -

Functions and Methods

- -

-Why do T and *T have different method sets?

- -

-As the Go specification says, -the method set of a type T consists of all methods -with receiver type T, -while that of the corresponding pointer -type *T consists of all methods with receiver *T or -T. -That means the method set of *T -includes that of T, -but not the reverse. -

- -

-This distinction arises because -if an interface value contains a pointer *T, -a method call can obtain a value by dereferencing the pointer, -but if an interface value contains a value T, -there is no safe way for a method call to obtain a pointer. -(Doing so would allow a method to modify the contents of -the value inside the interface, which is not permitted by -the language specification.) -

- -

-Even in cases where the compiler could take the address of a value -to pass to the method, if the method modifies the value the changes -will be lost in the caller. -As an example, if the Write method of -bytes.Buffer -used a value receiver rather than a pointer, -this code: -

- -
-var buf bytes.Buffer
-io.Copy(buf, os.Stdin)
-
- -

-would copy standard input into a copy of buf, -not into buf itself. -This is almost never the desired behavior. -

- -

-What happens with closures running as goroutines?

- -

-Some confusion may arise when using closures with concurrency. -Consider the following program: -

- -
-func main() {
-    done := make(chan bool)
-
-    values := []string{"a", "b", "c"}
-    for _, v := range values {
-        go func() {
-            fmt.Println(v)
-            done <- true
-        }()
-    }
-
-    // wait for all goroutines to complete before exiting
-    for _ = range values {
-        <-done
-    }
-}
-
- -

-One might mistakenly expect to see a, b, c as the output. -What you'll probably see instead is c, c, c. This is because -each iteration of the loop uses the same instance of the variable v, so -each closure shares that single variable. When the closure runs, it prints the -value of v at the time fmt.Println is executed, -but v may have been modified since the goroutine was launched. -To help detect this and other problems before they happen, run -go vet. -

- -

-To bind the current value of v to each closure as it is launched, one -must modify the inner loop to create a new variable each iteration. -One way is to pass the variable as an argument to the closure: -

- -
-    for _, v := range values {
-        go func(u string) {
-            fmt.Println(u)
-            done <- true
-        }(v)
-    }
-
- -

-In this example, the value of v is passed as an argument to the -anonymous function. That value is then accessible inside the function as -the variable u. -

- -

-Even easier is just to create a new variable, using a declaration style that may -seem odd but works fine in Go: -

- -
-    for _, v := range values {
-        v := v // create a new 'v'.
-        go func() {
-            fmt.Println(v)
-            done <- true
-        }()
-    }
-
- -

-This behavior of the language, not defining a new variable for -each iteration, may have been a mistake in retrospect. -It may be addressed in a later version but, for compatibility, -cannot change in Go version 1. -

- -

Control flow

- -

-Why does Go not have the ?: operator?

- -

-There is no ternary testing operation in Go. -You may use the following to achieve the same -result: -

- -
-if expr {
-    n = trueVal
-} else {
-    n = falseVal
-}
-
- -

-The reason ?: is absent from Go is that the language's designers -had seen the operation used too often to create impenetrably complex expressions. -The if-else form, although longer, -is unquestionably clearer. -A language needs only one conditional control flow construct. -

- -

Packages and Testing

- -

-How do I create a multifile package?

- -

-Put all the source files for the package in a directory by themselves. -Source files can refer to items from different files at will; there is -no need for forward declarations or a header file. -

- -

-Other than being split into multiple files, the package will compile and test -just like a single-file package. -

- -

-How do I write a unit test?

- -

-Create a new file ending in _test.go in the same directory -as your package sources. Inside that file, import "testing" -and write functions of the form -

- -
-func TestFoo(t *testing.T) {
-    ...
-}
-
- -

-Run go test in that directory. -That script finds the Test functions, -builds a test binary, and runs it. -

- -

See the How to Write Go Code document, -the testing package -and the go test subcommand for more details. -

- -

-Where is my favorite helper function for testing?

- -

-Go's standard testing package makes it easy to write unit tests, but it lacks -features provided in other language's testing frameworks such as assertion functions. -An earlier section of this document explained why Go -doesn't have assertions, and -the same arguments apply to the use of assert in tests. -Proper error handling means letting other tests run after one has failed, so -that the person debugging the failure gets a complete picture of what is -wrong. It is more useful for a test to report that -isPrime gives the wrong answer for 2, 3, 5, and 7 (or for -2, 4, 8, and 16) than to report that isPrime gives the wrong -answer for 2 and therefore no more tests were run. The programmer who -triggers the test failure may not be familiar with the code that fails. -Time invested writing a good error message now pays off later when the -test breaks. -

- -

-A related point is that testing frameworks tend to develop into mini-languages -of their own, with conditionals and controls and printing mechanisms, -but Go already has all those capabilities; why recreate them? -We'd rather write tests in Go; it's one fewer language to learn and the -approach keeps the tests straightforward and easy to understand. -

- -

-If the amount of extra code required to write -good errors seems repetitive and overwhelming, the test might work better if -table-driven, iterating over a list of inputs and outputs defined -in a data structure (Go has excellent support for data structure literals). -The work to write a good test and good error messages will then be amortized over many -test cases. The standard Go library is full of illustrative examples, such as in -the formatting tests for the fmt package. -

- -

-Why isn't X in the standard library?

- -

-The standard library's purpose is to support the runtime, connect to -the operating system, and provide key functionality that many Go -programs require, such as formatted I/O and networking. -It also contains elements important for web programming, including -cryptography and support for standards like HTTP, JSON, and XML. -

- -

-There is no clear criterion that defines what is included because for -a long time, this was the only Go library. -There are criteria that define what gets added today, however. -

- -

-New additions to the standard library are rare and the bar for -inclusion is high. -Code included in the standard library bears a large ongoing maintenance cost -(often borne by those other than the original author), -is subject to the Go 1 compatibility promise -(blocking fixes to any flaws in the API), -and is subject to the Go -release schedule, -preventing bug fixes from being available to users quickly. -

- -

-Most new code should live outside of the standard library and be accessible -via the go tool's -go get command. -Such code can have its own maintainers, release cycle, -and compatibility guarantees. -Users can find packages and read their documentation at -godoc.org. -

- -

-Although there are pieces in the standard library that don't really belong, -such as log/syslog, we continue to maintain everything in the -library because of the Go 1 compatibility promise. -But we encourage most new code to live elsewhere. -

- -

Implementation

- -

-What compiler technology is used to build the compilers?

- -

-There are several production compilers for Go, and a number of others -in development for various platforms. -

- -

-The default compiler, gc, is included with the -Go distribution as part of the support for the go -command. -Gc was originally written in C -because of the difficulties of bootstrapping—you'd need a Go compiler to -set up a Go environment. -But things have advanced and since the Go 1.5 release the compiler has been -a Go program. -The compiler was converted from C to Go using automatic translation tools, as -described in this design document -and talk. -Thus the compiler is now "self-hosting", which means we needed to face -the bootstrapping problem. -The solution is to have a working Go installation already in place, -just as one normally has with a working C installation. -The story of how to bring up a new Go environment from source -is described here and -here. -

- -

-Gc is written in Go with a recursive descent parser -and uses a custom loader, also written in Go but -based on the Plan 9 loader, to generate ELF/Mach-O/PE binaries. -

- -

-At the beginning of the project we considered using LLVM for -gc but decided it was too large and slow to meet -our performance goals. -More important in retrospect, starting with LLVM would have made it -harder to introduce some of the ABI and related changes, such as -stack management, that Go requires but are not part of the standard -C setup. -A new LLVM implementation -is starting to come together now, however. -

- -

-The Gccgo compiler is a front end written in C++ -with a recursive descent parser coupled to the -standard GCC back end. -

- -

-Go turned out to be a fine language in which to implement a Go compiler, -although that was not its original goal. -Not being self-hosting from the beginning allowed Go's design to -concentrate on its original use case, which was networked servers. -Had we decided Go should compile itself early on, we might have -ended up with a language targeted more for compiler construction, -which is a worthy goal but not the one we had initially. -

- -

-Although gc does not use them (yet?), a native lexer and -parser are available in the go package -and there is also a native type checker. -

- -

-How is the run-time support implemented?

- -

-Again due to bootstrapping issues, the run-time code was originally written mostly in C (with a -tiny bit of assembler) but it has since been translated to Go -(except for some assembler bits). -Gccgo's run-time support uses glibc. -The gccgo compiler implements goroutines using -a technique called segmented stacks, -supported by recent modifications to the gold linker. -Gollvm similarly is built on the corresponding -LLVM infrastructure. -

- -

-Why is my trivial program such a large binary?

- -

-The linker in the gc toolchain -creates statically-linked binaries by default. -All Go binaries therefore include the Go -runtime, along with the run-time type information necessary to support dynamic -type checks, reflection, and even panic-time stack traces. -

- -

-A simple C "hello, world" program compiled and linked statically using -gcc on Linux is around 750 kB, including an implementation of -printf. -An equivalent Go program using -fmt.Printf weighs a couple of megabytes, but that includes -more powerful run-time support and type and debugging information. -

- -

-A Go program compiled with gc can be linked with -the -ldflags=-w flag to disable DWARF generation, -removing debugging information from the binary but with no -other loss of functionality. -This can reduce the binary size substantially. -

- -

-Can I stop these complaints about my unused variable/import?

- -

-The presence of an unused variable may indicate a bug, while -unused imports just slow down compilation, -an effect that can become substantial as a program accumulates -code and programmers over time. -For these reasons, Go refuses to compile programs with unused -variables or imports, -trading short-term convenience for long-term build speed and -program clarity. -

- -

-Still, when developing code, it's common to create these situations -temporarily and it can be annoying to have to edit them out before the -program will compile. -

- -

-Some have asked for a compiler option to turn those checks off -or at least reduce them to warnings. -Such an option has not been added, though, -because compiler options should not affect the semantics of the -language and because the Go compiler does not report warnings, only -errors that prevent compilation. -

- -

-There are two reasons for having no warnings. First, if it's worth -complaining about, it's worth fixing in the code. (And if it's not -worth fixing, it's not worth mentioning.) Second, having the compiler -generate warnings encourages the implementation to warn about weak -cases that can make compilation noisy, masking real errors that -should be fixed. -

- -

-It's easy to address the situation, though. Use the blank identifier -to let unused things persist while you're developing. -

- -
-import "unused"
-
-// This declaration marks the import as used by referencing an
-// item from the package.
-var _ = unused.Item  // TODO: Delete before committing!
-
-func main() {
-    debugData := debug.Profile()
-    _ = debugData // Used only during debugging.
-    ....
-}
-
- -

-Nowadays, most Go programmers use a tool, -goimports, -which automatically rewrites a Go source file to have the correct imports, -eliminating the unused imports issue in practice. -This program is easily connected to most editors to run automatically when a Go source file is written. -

- -

-Why does my virus-scanning software think my Go distribution or compiled binary is infected?

- -

-This is a common occurrence, especially on Windows machines, and is almost always a false positive. -Commercial virus scanning programs are often confused by the structure of Go binaries, which -they don't see as often as those compiled from other languages. -

- -

-If you've just installed the Go distribution and the system reports it is infected, that's certainly a mistake. -To be really thorough, you can verify the download by comparing the checksum with those on the -downloads page. -

- -

-In any case, if you believe the report is in error, please report a bug to the supplier of your virus scanner. -Maybe in time virus scanners can learn to understand Go programs. -

- -

Performance

- -

-Why does Go perform badly on benchmark X?

- -

-One of Go's design goals is to approach the performance of C for comparable -programs, yet on some benchmarks it does quite poorly, including several -in golang.org/x/exp/shootout. -The slowest depend on libraries for which versions of comparable performance -are not available in Go. -For instance, pidigits.go -depends on a multi-precision math package, and the C -versions, unlike Go's, use GMP (which is -written in optimized assembler). -Benchmarks that depend on regular expressions -(regex-dna.go, -for instance) are essentially comparing Go's native regexp package to -mature, highly optimized regular expression libraries like PCRE. -

- -

-Benchmark games are won by extensive tuning and the Go versions of most -of the benchmarks need attention. If you measure comparable C -and Go programs -(reverse-complement.go -is one example), you'll see the two languages are much closer in raw performance -than this suite would indicate. -

- -

-Still, there is room for improvement. The compilers are good but could be -better, many libraries need major performance work, and the garbage collector -isn't fast enough yet. (Even if it were, taking care not to generate unnecessary -garbage can have a huge effect.) -

- -

-In any case, Go can often be very competitive. -There has been significant improvement in the performance of many programs -as the language and tools have developed. -See the blog post about -profiling -Go programs for an informative example. - -

Changes from C

- -

-Why is the syntax so different from C?

-

-Other than declaration syntax, the differences are not major and stem -from two desires. First, the syntax should feel light, without too -many mandatory keywords, repetition, or arcana. Second, the language -has been designed to be easy to analyze -and can be parsed without a symbol table. This makes it much easier -to build tools such as debuggers, dependency analyzers, automated -documentation extractors, IDE plug-ins, and so on. C and its -descendants are notoriously difficult in this regard. -

- -

-Why are declarations backwards?

-

-They're only backwards if you're used to C. In C, the notion is that a -variable is declared like an expression denoting its type, which is a -nice idea, but the type and expression grammars don't mix very well and -the results can be confusing; consider function pointers. Go mostly -separates expression and type syntax and that simplifies things (using -prefix * for pointers is an exception that proves the rule). In C, -the declaration -

-
-    int* a, b;
-
-

-declares a to be a pointer but not b; in Go -

-
-    var a, b *int
-
-

-declares both to be pointers. This is clearer and more regular. -Also, the := short declaration form argues that a full variable -declaration should present the same order as := so -

-
-    var a uint64 = 1
-
-

-has the same effect as -

-
-    a := uint64(1)
-
-

-Parsing is also simplified by having a distinct grammar for types that -is not just the expression grammar; keywords such as func -and chan keep things clear. -

- -

-See the article about -Go's Declaration Syntax -for more details. -

- -

-Why is there no pointer arithmetic?

-

-Safety. Without pointer arithmetic it's possible to create a -language that can never derive an illegal address that succeeds -incorrectly. Compiler and hardware technology have advanced to the -point where a loop using array indices can be as efficient as a loop -using pointer arithmetic. Also, the lack of pointer arithmetic can -simplify the implementation of the garbage collector. -

- -

-Why are ++ and -- statements and not expressions? And why postfix, not prefix?

-

-Without pointer arithmetic, the convenience value of pre- and postfix -increment operators drops. By removing them from the expression -hierarchy altogether, expression syntax is simplified and the messy -issues around order of evaluation of ++ and -- -(consider f(i++) and p[i] = q[++i]) -are eliminated as well. The simplification is -significant. As for postfix vs. prefix, either would work fine but -the postfix version is more traditional; insistence on prefix arose -with the STL, a library for a language whose name contains, ironically, a -postfix increment. -

- -

-Why are there braces but no semicolons? And why can't I put the opening -brace on the next line?

-

-Go uses brace brackets for statement grouping, a syntax familiar to -programmers who have worked with any language in the C family. -Semicolons, however, are for parsers, not for people, and we wanted to -eliminate them as much as possible. To achieve this goal, Go borrows -a trick from BCPL: the semicolons that separate statements are in the -formal grammar but are injected automatically, without lookahead, by -the lexer at the end of any line that could be the end of a statement. -This works very well in practice but has the effect that it forces a -brace style. For instance, the opening brace of a function cannot -appear on a line by itself. -

- -

-Some have argued that the lexer should do lookahead to permit the -brace to live on the next line. We disagree. Since Go code is meant -to be formatted automatically by -gofmt, -some style must be chosen. That style may differ from what -you've used in C or Java, but Go is a different language and -gofmt's style is as good as any other. More -important—much more important—the advantages of a single, -programmatically mandated format for all Go programs greatly outweigh -any perceived disadvantages of the particular style. -Note too that Go's style means that an interactive implementation of -Go can use the standard syntax one line at a time without special rules. -

- -

-Why do garbage collection? Won't it be too expensive?

-

-One of the biggest sources of bookkeeping in systems programs is -managing the lifetimes of allocated objects. -In languages such as C in which it is done manually, -it can consume a significant amount of programmer time and is -often the cause of pernicious bugs. -Even in languages like C++ or Rust that provide mechanisms -to assist, those mechanisms can have a significant effect on the -design of the software, often adding programming overhead -of its own. -We felt it was critical to eliminate such -programmer overheads, and advances in garbage collection -technology in the last few years gave us confidence that it -could be implemented cheaply enough, and with low enough -latency, that it could be a viable approach for networked -systems. -

- -

-Much of the difficulty of concurrent programming -has its roots in the object lifetime problem: -as objects get passed among threads it becomes cumbersome -to guarantee they become freed safely. -Automatic garbage collection makes concurrent code far easier to write. -Of course, implementing garbage collection in a concurrent environment is -itself a challenge, but meeting it once rather than in every -program helps everyone. -

- -

-Finally, concurrency aside, garbage collection makes interfaces -simpler because they don't need to specify how memory is managed across them. -

- -

-This is not to say that the recent work in languages -like Rust that bring new ideas to the problem of managing -resources is misguided; we encourage this work and are excited to see -how it evolves. -But Go takes a more traditional approach by addressing -object lifetimes through -garbage collection, and garbage collection alone. -

- -

-The current implementation is a mark-and-sweep collector. -If the machine is a multiprocessor, the collector runs on a separate CPU -core in parallel with the main program. -Major work on the collector in recent years has reduced pause times -often to the sub-millisecond range, even for large heaps, -all but eliminating one of the major objections to garbage collection -in networked servers. -Work continues to refine the algorithm, reduce overhead and -latency further, and to explore new approaches. -The 2018 -ISMM keynote -by Rick Hudson of the Go team -describes the progress so far and suggests some future approaches. -

- -

-On the topic of performance, keep in mind that Go gives the programmer -considerable control over memory layout and allocation, much more than -is typical in garbage-collected languages. A careful programmer can reduce -the garbage collection overhead dramatically by using the language well; -see the article about -profiling -Go programs for a worked example, including a demonstration of Go's -profiling tools. -

diff --git a/doc/gopher/README b/doc/gopher/README deleted file mode 100644 index d4ca8a1c2d..0000000000 --- a/doc/gopher/README +++ /dev/null @@ -1,3 +0,0 @@ -The Go gopher was designed by Renee French. (http://reneefrench.blogspot.com/) -The design is licensed under the Creative Commons 3.0 Attributions license. -Read this article for more details: https://blog.golang.org/gopher diff --git a/doc/gopher/appenginegopher.jpg b/doc/gopher/appenginegopher.jpg deleted file mode 100644 index 0a64306666..0000000000 Binary files a/doc/gopher/appenginegopher.jpg and /dev/null differ diff --git a/doc/gopher/appenginegophercolor.jpg b/doc/gopher/appenginegophercolor.jpg deleted file mode 100644 index 68795a99b3..0000000000 Binary files a/doc/gopher/appenginegophercolor.jpg and /dev/null differ diff --git a/doc/gopher/appenginelogo.gif b/doc/gopher/appenginelogo.gif deleted file mode 100644 index 46b3c1eeb8..0000000000 Binary files a/doc/gopher/appenginelogo.gif and /dev/null differ diff --git a/doc/gopher/biplane.jpg b/doc/gopher/biplane.jpg deleted file mode 100644 index d5e666f963..0000000000 Binary files a/doc/gopher/biplane.jpg and /dev/null differ diff --git a/doc/gopher/bumper.png b/doc/gopher/bumper.png deleted file mode 100644 index b357cdf47d..0000000000 Binary files a/doc/gopher/bumper.png and /dev/null differ diff --git a/doc/gopher/bumper192x108.png b/doc/gopher/bumper192x108.png deleted file mode 100644 index 925474e763..0000000000 Binary files a/doc/gopher/bumper192x108.png and /dev/null differ diff --git a/doc/gopher/bumper320x180.png b/doc/gopher/bumper320x180.png deleted file mode 100644 index 611c417c4f..0000000000 Binary files a/doc/gopher/bumper320x180.png and /dev/null differ diff --git a/doc/gopher/bumper480x270.png b/doc/gopher/bumper480x270.png deleted file mode 100644 index cf187151fd..0000000000 Binary files a/doc/gopher/bumper480x270.png and /dev/null differ diff --git a/doc/gopher/bumper640x360.png b/doc/gopher/bumper640x360.png deleted file mode 100644 index a5073e0d1a..0000000000 Binary files a/doc/gopher/bumper640x360.png and /dev/null differ diff --git a/doc/gopher/doc.png b/doc/gopher/doc.png deleted file mode 100644 index e15a3234d5..0000000000 Binary files a/doc/gopher/doc.png and /dev/null differ diff --git a/doc/gopher/favicon.svg b/doc/gopher/favicon.svg deleted file mode 100644 index e5a68fe29e..0000000000 --- a/doc/gopher/favicon.svg +++ /dev/null @@ -1,238 +0,0 @@ - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/doc/gopher/fiveyears.jpg b/doc/gopher/fiveyears.jpg deleted file mode 100644 index df1064868e..0000000000 Binary files a/doc/gopher/fiveyears.jpg and /dev/null differ diff --git a/doc/gopher/frontpage.png b/doc/gopher/frontpage.png deleted file mode 100644 index 1eb81f0bef..0000000000 Binary files a/doc/gopher/frontpage.png and /dev/null differ diff --git a/doc/gopher/gopherbw.png b/doc/gopher/gopherbw.png deleted file mode 100644 index 3bfe85dc16..0000000000 Binary files a/doc/gopher/gopherbw.png and /dev/null differ diff --git a/doc/gopher/gophercolor.png b/doc/gopher/gophercolor.png deleted file mode 100644 index b5f8d01ff6..0000000000 Binary files a/doc/gopher/gophercolor.png and /dev/null differ diff --git a/doc/gopher/gophercolor16x16.png b/doc/gopher/gophercolor16x16.png deleted file mode 100644 index ec7028cc11..0000000000 Binary files a/doc/gopher/gophercolor16x16.png and /dev/null differ diff --git a/doc/gopher/help.png b/doc/gopher/help.png deleted file mode 100644 index 6ee523898d..0000000000 Binary files a/doc/gopher/help.png and /dev/null differ diff --git a/doc/gopher/modelsheet.jpg b/doc/gopher/modelsheet.jpg deleted file mode 100644 index c31e35a6df..0000000000 Binary files a/doc/gopher/modelsheet.jpg and /dev/null differ diff --git a/doc/gopher/pencil/gopherhat.jpg b/doc/gopher/pencil/gopherhat.jpg deleted file mode 100644 index f34d7b3258..0000000000 Binary files a/doc/gopher/pencil/gopherhat.jpg and /dev/null differ diff --git a/doc/gopher/pencil/gopherhelmet.jpg b/doc/gopher/pencil/gopherhelmet.jpg deleted file mode 100644 index c7b6c61b2b..0000000000 Binary files a/doc/gopher/pencil/gopherhelmet.jpg and /dev/null differ diff --git a/doc/gopher/pencil/gophermega.jpg b/doc/gopher/pencil/gophermega.jpg deleted file mode 100644 index 779fb073ac..0000000000 Binary files a/doc/gopher/pencil/gophermega.jpg and /dev/null differ diff --git a/doc/gopher/pencil/gopherrunning.jpg b/doc/gopher/pencil/gopherrunning.jpg deleted file mode 100644 index eeeddf106f..0000000000 Binary files a/doc/gopher/pencil/gopherrunning.jpg and /dev/null differ diff --git a/doc/gopher/pencil/gopherswim.jpg b/doc/gopher/pencil/gopherswim.jpg deleted file mode 100644 index 2f32877121..0000000000 Binary files a/doc/gopher/pencil/gopherswim.jpg and /dev/null differ diff --git a/doc/gopher/pencil/gopherswrench.jpg b/doc/gopher/pencil/gopherswrench.jpg deleted file mode 100644 index 93005f42a8..0000000000 Binary files a/doc/gopher/pencil/gopherswrench.jpg and /dev/null differ diff --git a/doc/gopher/pkg.png b/doc/gopher/pkg.png deleted file mode 100644 index ac96551b55..0000000000 Binary files a/doc/gopher/pkg.png and /dev/null differ diff --git a/doc/gopher/project.png b/doc/gopher/project.png deleted file mode 100644 index 24603f3068..0000000000 Binary files a/doc/gopher/project.png and /dev/null differ diff --git a/doc/gopher/ref.png b/doc/gopher/ref.png deleted file mode 100644 index 0508f6ec61..0000000000 Binary files a/doc/gopher/ref.png and /dev/null differ diff --git a/doc/gopher/run.png b/doc/gopher/run.png deleted file mode 100644 index eb690e3f22..0000000000 Binary files a/doc/gopher/run.png and /dev/null differ diff --git a/doc/gopher/talks.png b/doc/gopher/talks.png deleted file mode 100644 index 589db470a7..0000000000 Binary files a/doc/gopher/talks.png and /dev/null differ diff --git a/doc/help.html b/doc/help.html deleted file mode 100644 index 3d32ae5dc0..0000000000 --- a/doc/help.html +++ /dev/null @@ -1,96 +0,0 @@ - - -
- -

Get help

- - - -{{if not $.GoogleCN}} -

Go Nuts Mailing List

-

-Get help from Go users, and share your work on the official mailing list. -

-

-Search the golang-nuts -archives and consult the FAQ and -wiki before posting. -

- -

Go Forum

-

-The Go Forum is a discussion -forum for Go programmers. -

- -

Gophers Discord

-

-Get live support and talk with other gophers on the Go Discord. -

- -

Gopher Slack

-

Get live support from other users in the Go slack channel.

- -

Go IRC Channel

-

Get live support at #go-nuts on irc.freenode.net, the official -Go IRC channel.

-{{end}} - -

Frequently Asked Questions (FAQ)

-

Answers to common questions about Go.

- -{{if not $.GoogleCN}} -

Stay informed

- -

Go Announcements Mailing List

-

-Subscribe to -golang-announce -for important announcements, such as the availability of new Go releases. -

- -

Go Blog

-

The Go project's official blog.

- -

@golang at Twitter

-

The Go project's official Twitter account.

- -

golang sub-Reddit

-

-The golang sub-Reddit is a place -for Go news and discussion. -

- -

Go Time Podcast

-

-The Go Time podcast is a panel of Go experts and special guests -discussing the Go programming language, the community, and everything in between. -

-{{end}} - -

Community resources

- -

Go User Groups

-

-Each month in places around the world, groups of Go programmers ("gophers") -meet to talk about Go. Find a chapter near you. -

- -{{if not $.GoogleCN}} -

Go Playground

-

A place to write, run, and share Go code.

- -

Go Wiki

-

A wiki maintained by the Go community.

-{{end}} - -

Code of Conduct

-

-Guidelines for participating in Go community spaces -and a reporting process for handling issues. -

- diff --git a/doc/ie.css b/doc/ie.css deleted file mode 100644 index bb89d54be2..0000000000 --- a/doc/ie.css +++ /dev/null @@ -1 +0,0 @@ -#nav-main li { display: inline; } diff --git a/doc/play/fib.go b/doc/play/fib.go deleted file mode 100644 index 19e4721028..0000000000 --- a/doc/play/fib.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import "fmt" - -// fib returns a function that returns -// successive Fibonacci numbers. -func fib() func() int { - a, b := 0, 1 - return func() int { - a, b = b, a+b - return a - } -} - -func main() { - f := fib() - // Function calls are evaluated left-to-right. - fmt.Println(f(), f(), f(), f(), f()) -} diff --git a/doc/play/hello.go b/doc/play/hello.go deleted file mode 100644 index 3badf12538..0000000000 --- a/doc/play/hello.go +++ /dev/null @@ -1,9 +0,0 @@ -// You can edit this code! -// Click here and start typing. -package main - -import "fmt" - -func main() { - fmt.Println("Hello, 世界") -} diff --git a/doc/play/life.go b/doc/play/life.go deleted file mode 100644 index 51afb61f3d..0000000000 --- a/doc/play/life.go +++ /dev/null @@ -1,113 +0,0 @@ -// An implementation of Conway's Game of Life. -package main - -import ( - "bytes" - "fmt" - "math/rand" - "time" -) - -// Field represents a two-dimensional field of cells. -type Field struct { - s [][]bool - w, h int -} - -// NewField returns an empty field of the specified width and height. -func NewField(w, h int) *Field { - s := make([][]bool, h) - for i := range s { - s[i] = make([]bool, w) - } - return &Field{s: s, w: w, h: h} -} - -// Set sets the state of the specified cell to the given value. -func (f *Field) Set(x, y int, b bool) { - f.s[y][x] = b -} - -// Alive reports whether the specified cell is alive. -// If the x or y coordinates are outside the field boundaries they are wrapped -// toroidally. For instance, an x value of -1 is treated as width-1. -func (f *Field) Alive(x, y int) bool { - x += f.w - x %= f.w - y += f.h - y %= f.h - return f.s[y][x] -} - -// Next returns the state of the specified cell at the next time step. -func (f *Field) Next(x, y int) bool { - // Count the adjacent cells that are alive. - alive := 0 - for i := -1; i <= 1; i++ { - for j := -1; j <= 1; j++ { - if (j != 0 || i != 0) && f.Alive(x+i, y+j) { - alive++ - } - } - } - // Return next state according to the game rules: - // exactly 3 neighbors: on, - // exactly 2 neighbors: maintain current state, - // otherwise: off. - return alive == 3 || alive == 2 && f.Alive(x, y) -} - -// Life stores the state of a round of Conway's Game of Life. -type Life struct { - a, b *Field - w, h int -} - -// NewLife returns a new Life game state with a random initial state. -func NewLife(w, h int) *Life { - a := NewField(w, h) - for i := 0; i < (w * h / 4); i++ { - a.Set(rand.Intn(w), rand.Intn(h), true) - } - return &Life{ - a: a, b: NewField(w, h), - w: w, h: h, - } -} - -// Step advances the game by one instant, recomputing and updating all cells. -func (l *Life) Step() { - // Update the state of the next field (b) from the current field (a). - for y := 0; y < l.h; y++ { - for x := 0; x < l.w; x++ { - l.b.Set(x, y, l.a.Next(x, y)) - } - } - // Swap fields a and b. - l.a, l.b = l.b, l.a -} - -// String returns the game board as a string. -func (l *Life) String() string { - var buf bytes.Buffer - for y := 0; y < l.h; y++ { - for x := 0; x < l.w; x++ { - b := byte(' ') - if l.a.Alive(x, y) { - b = '*' - } - buf.WriteByte(b) - } - buf.WriteByte('\n') - } - return buf.String() -} - -func main() { - l := NewLife(40, 15) - for i := 0; i < 300; i++ { - l.Step() - fmt.Print("\x0c", l) // Clear screen and print field. - time.Sleep(time.Second / 30) - } -} diff --git a/doc/play/peano.go b/doc/play/peano.go deleted file mode 100644 index 214fe1b613..0000000000 --- a/doc/play/peano.go +++ /dev/null @@ -1,88 +0,0 @@ -// Peano integers are represented by a linked -// list whose nodes contain no data -// (the nodes are the data). -// http://en.wikipedia.org/wiki/Peano_axioms - -// This program demonstrates that Go's automatic -// stack management can handle heavily recursive -// computations. - -package main - -import "fmt" - -// Number is a pointer to a Number -type Number *Number - -// The arithmetic value of a Number is the -// count of the nodes comprising the list. -// (See the count function below.) - -// ------------------------------------- -// Peano primitives - -func zero() *Number { - return nil -} - -func isZero(x *Number) bool { - return x == nil -} - -func add1(x *Number) *Number { - e := new(Number) - *e = x - return e -} - -func sub1(x *Number) *Number { - return *x -} - -func add(x, y *Number) *Number { - if isZero(y) { - return x - } - return add(add1(x), sub1(y)) -} - -func mul(x, y *Number) *Number { - if isZero(x) || isZero(y) { - return zero() - } - return add(mul(x, sub1(y)), x) -} - -func fact(n *Number) *Number { - if isZero(n) { - return add1(zero()) - } - return mul(fact(sub1(n)), n) -} - -// ------------------------------------- -// Helpers to generate/count Peano integers - -func gen(n int) *Number { - if n > 0 { - return add1(gen(n - 1)) - } - return zero() -} - -func count(x *Number) int { - if isZero(x) { - return 0 - } - return count(sub1(x)) + 1 -} - -// ------------------------------------- -// Print i! for i in [0,9] - -func main() { - for i := 0; i <= 9; i++ { - f := count(fact(gen(i))) - fmt.Println(i, "! =", f) - } -} diff --git a/doc/play/pi.go b/doc/play/pi.go deleted file mode 100644 index f61884e888..0000000000 --- a/doc/play/pi.go +++ /dev/null @@ -1,34 +0,0 @@ -// Concurrent computation of pi. -// See https://goo.gl/la6Kli. -// -// This demonstrates Go's ability to handle -// large numbers of concurrent processes. -// It is an unreasonable way to calculate pi. -package main - -import ( - "fmt" - "math" -) - -func main() { - fmt.Println(pi(5000)) -} - -// pi launches n goroutines to compute an -// approximation of pi. -func pi(n int) float64 { - ch := make(chan float64) - for k := 0; k <= n; k++ { - go term(ch, float64(k)) - } - f := 0.0 - for k := 0; k <= n; k++ { - f += <-ch - } - return f -} - -func term(ch chan float64, k float64) { - ch <- 4 * math.Pow(-1, k) / (2*k + 1) -} diff --git a/doc/play/sieve.go b/doc/play/sieve.go deleted file mode 100644 index 519093453f..0000000000 --- a/doc/play/sieve.go +++ /dev/null @@ -1,36 +0,0 @@ -// A concurrent prime sieve - -package main - -import "fmt" - -// Send the sequence 2, 3, 4, ... to channel 'ch'. -func Generate(ch chan<- int) { - for i := 2; ; i++ { - ch <- i // Send 'i' to channel 'ch'. - } -} - -// Copy the values from channel 'in' to channel 'out', -// removing those divisible by 'prime'. -func Filter(in <-chan int, out chan<- int, prime int) { - for { - i := <-in // Receive value from 'in'. - if i%prime != 0 { - out <- i // Send 'i' to 'out'. - } - } -} - -// The prime sieve: Daisy-chain Filter processes. -func main() { - ch := make(chan int) // Create a new channel. - go Generate(ch) // Launch Generate goroutine. - for i := 0; i < 10; i++ { - prime := <-ch - fmt.Println(prime) - ch1 := make(chan int) - go Filter(ch, ch1, prime) - ch = ch1 - } -} diff --git a/doc/play/solitaire.go b/doc/play/solitaire.go deleted file mode 100644 index 15022aa194..0000000000 --- a/doc/play/solitaire.go +++ /dev/null @@ -1,117 +0,0 @@ -// This program solves the (English) peg -// solitaire board game. -// http://en.wikipedia.org/wiki/Peg_solitaire - -package main - -import "fmt" - -const N = 11 + 1 // length of a row (+1 for \n) - -// The board must be surrounded by 2 illegal -// fields in each direction so that move() -// doesn't need to check the board boundaries. -// Periods represent illegal fields, -// ● are pegs, and ○ are holes. - -var board = []rune( - `........... -........... -....●●●.... -....●●●.... -..●●●●●●●.. -..●●●○●●●.. -..●●●●●●●.. -....●●●.... -....●●●.... -........... -........... -`) - -// center is the position of the center hole if -// there is a single one; otherwise it is -1. -var center int - -func init() { - n := 0 - for pos, field := range board { - if field == '○' { - center = pos - n++ - } - } - if n != 1 { - center = -1 // no single hole - } -} - -var moves int // number of times move is called - -// move tests if there is a peg at position pos that -// can jump over another peg in direction dir. If the -// move is valid, it is executed and move returns true. -// Otherwise, move returns false. -func move(pos, dir int) bool { - moves++ - if board[pos] == '●' && board[pos+dir] == '●' && board[pos+2*dir] == '○' { - board[pos] = '○' - board[pos+dir] = '○' - board[pos+2*dir] = '●' - return true - } - return false -} - -// unmove reverts a previously executed valid move. -func unmove(pos, dir int) { - board[pos] = '●' - board[pos+dir] = '●' - board[pos+2*dir] = '○' -} - -// solve tries to find a sequence of moves such that -// there is only one peg left at the end; if center is -// >= 0, that last peg must be in the center position. -// If a solution is found, solve prints the board after -// each move in a backward fashion (i.e., the last -// board position is printed first, all the way back to -// the starting board position). -func solve() bool { - var last, n int - for pos, field := range board { - // try each board position - if field == '●' { - // found a peg - for _, dir := range [...]int{-1, -N, +1, +N} { - // try each direction - if move(pos, dir) { - // a valid move was found and executed, - // see if this new board has a solution - if solve() { - unmove(pos, dir) - fmt.Println(string(board)) - return true - } - unmove(pos, dir) - } - } - last = pos - n++ - } - } - // tried each possible move - if n == 1 && (center < 0 || last == center) { - // there's only one peg left - fmt.Println(string(board)) - return true - } - // no solution found for this board - return false -} - -func main() { - if !solve() { - fmt.Println("no solution found") - } - fmt.Println(moves, "moves tried") -} diff --git a/doc/play/tree.go b/doc/play/tree.go deleted file mode 100644 index 3790e6cda5..0000000000 --- a/doc/play/tree.go +++ /dev/null @@ -1,100 +0,0 @@ -// Go's concurrency primitives make it easy to -// express concurrent concepts, such as -// this binary tree comparison. -// -// Trees may be of different shapes, -// but have the same contents. For example: -// -// 4 6 -// 2 6 4 7 -// 1 3 5 7 2 5 -// 1 3 -// -// This program compares a pair of trees by -// walking each in its own goroutine, -// sending their contents through a channel -// to a third goroutine that compares them. - -package main - -import ( - "fmt" - "math/rand" -) - -// A Tree is a binary tree with integer values. -type Tree struct { - Left *Tree - Value int - Right *Tree -} - -// Walk traverses a tree depth-first, -// sending each Value on a channel. -func Walk(t *Tree, ch chan int) { - if t == nil { - return - } - Walk(t.Left, ch) - ch <- t.Value - Walk(t.Right, ch) -} - -// Walker launches Walk in a new goroutine, -// and returns a read-only channel of values. -func Walker(t *Tree) <-chan int { - ch := make(chan int) - go func() { - Walk(t, ch) - close(ch) - }() - return ch -} - -// Compare reads values from two Walkers -// that run simultaneously, and returns true -// if t1 and t2 have the same contents. -func Compare(t1, t2 *Tree) bool { - c1, c2 := Walker(t1), Walker(t2) - for { - v1, ok1 := <-c1 - v2, ok2 := <-c2 - if !ok1 || !ok2 { - return ok1 == ok2 - } - if v1 != v2 { - break - } - } - return false -} - -// New returns a new, random binary tree -// holding the values 1k, 2k, ..., nk. -func New(n, k int) *Tree { - var t *Tree - for _, v := range rand.Perm(n) { - t = insert(t, (1+v)*k) - } - return t -} - -func insert(t *Tree, v int) *Tree { - if t == nil { - return &Tree{nil, v, nil} - } - if v < t.Value { - t.Left = insert(t.Left, v) - return t - } - t.Right = insert(t.Right, v) - return t -} - -func main() { - t1 := New(100, 1) - fmt.Println(Compare(t1, New(100, 1)), "Same Contents") - fmt.Println(Compare(t1, New(99, 1)), "Differing Sizes") - fmt.Println(Compare(t1, New(100, 2)), "Differing Values") - fmt.Println(Compare(t1, New(101, 2)), "Dissimilar") -} diff --git a/doc/progs/cgo1.go b/doc/progs/cgo1.go deleted file mode 100644 index d559e13931..0000000000 --- a/doc/progs/cgo1.go +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package rand - -/* -#include -*/ -import "C" - -// STOP OMIT -func Random() int { - return int(C.rand()) -} - -// STOP OMIT -func Seed(i int) { - C.srand(C.uint(i)) -} - -// END OMIT diff --git a/doc/progs/cgo2.go b/doc/progs/cgo2.go deleted file mode 100644 index da07aa49e6..0000000000 --- a/doc/progs/cgo2.go +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package rand2 - -/* -#include -*/ -import "C" - -func Random() int { - var r C.int = C.rand() - return int(r) -} - -// STOP OMIT -func Seed(i int) { - C.srand(C.uint(i)) -} - -// END OMIT diff --git a/doc/progs/cgo3.go b/doc/progs/cgo3.go deleted file mode 100644 index d5cedf4960..0000000000 --- a/doc/progs/cgo3.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package print - -// #include -// #include -import "C" -import "unsafe" - -func Print(s string) { - cs := C.CString(s) - C.fputs(cs, (*C.FILE)(C.stdout)) - C.free(unsafe.Pointer(cs)) -} - -// END OMIT diff --git a/doc/progs/cgo4.go b/doc/progs/cgo4.go deleted file mode 100644 index dbb07e84fe..0000000000 --- a/doc/progs/cgo4.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package print - -// #include -// #include -import "C" -import "unsafe" - -func Print(s string) { - cs := C.CString(s) - defer C.free(unsafe.Pointer(cs)) - C.fputs(cs, (*C.FILE)(C.stdout)) -} - -// END OMIT diff --git a/doc/progs/defer.go b/doc/progs/defer.go deleted file mode 100644 index 2e11020abf..0000000000 --- a/doc/progs/defer.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file contains the code snippets included in "Defer, Panic, and Recover." - -package main - -import ( - "fmt" - "io" - "os" -) - -func a() { - i := 0 - defer fmt.Println(i) - i++ - return -} - -// STOP OMIT - -func b() { - for i := 0; i < 4; i++ { - defer fmt.Print(i) - } -} - -// STOP OMIT - -func c() (i int) { - defer func() { i++ }() - return 1 -} - -// STOP OMIT - -// Initial version. -func CopyFile(dstName, srcName string) (written int64, err error) { - src, err := os.Open(srcName) - if err != nil { - return - } - - dst, err := os.Create(dstName) - if err != nil { - return - } - - written, err = io.Copy(dst, src) - dst.Close() - src.Close() - return -} - -// STOP OMIT - -func main() { - a() - b() - fmt.Println() - fmt.Println(c()) -} diff --git a/doc/progs/defer2.go b/doc/progs/defer2.go deleted file mode 100644 index cad66b0702..0000000000 --- a/doc/progs/defer2.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file contains the code snippets included in "Defer, Panic, and Recover." - -package main - -import "fmt" -import "io" // OMIT -import "os" // OMIT - -func main() { - f() - fmt.Println("Returned normally from f.") -} - -func f() { - defer func() { - if r := recover(); r != nil { - fmt.Println("Recovered in f", r) - } - }() - fmt.Println("Calling g.") - g(0) - fmt.Println("Returned normally from g.") -} - -func g(i int) { - if i > 3 { - fmt.Println("Panicking!") - panic(fmt.Sprintf("%v", i)) - } - defer fmt.Println("Defer in g", i) - fmt.Println("Printing in g", i) - g(i + 1) -} - -// STOP OMIT - -// Revised version. -func CopyFile(dstName, srcName string) (written int64, err error) { - src, err := os.Open(srcName) - if err != nil { - return - } - defer src.Close() - - dst, err := os.Create(dstName) - if err != nil { - return - } - defer dst.Close() - - return io.Copy(dst, src) -} - -// STOP OMIT diff --git a/doc/progs/eff_bytesize.go b/doc/progs/eff_bytesize.go deleted file mode 100644 index b45961114d..0000000000 --- a/doc/progs/eff_bytesize.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import "fmt" - -type ByteSize float64 - -const ( - _ = iota // ignore first value by assigning to blank identifier - KB ByteSize = 1 << (10 * iota) - MB - GB - TB - PB - EB - ZB - YB -) - -func (b ByteSize) String() string { - switch { - case b >= YB: - return fmt.Sprintf("%.2fYB", b/YB) - case b >= ZB: - return fmt.Sprintf("%.2fZB", b/ZB) - case b >= EB: - return fmt.Sprintf("%.2fEB", b/EB) - case b >= PB: - return fmt.Sprintf("%.2fPB", b/PB) - case b >= TB: - return fmt.Sprintf("%.2fTB", b/TB) - case b >= GB: - return fmt.Sprintf("%.2fGB", b/GB) - case b >= MB: - return fmt.Sprintf("%.2fMB", b/MB) - case b >= KB: - return fmt.Sprintf("%.2fKB", b/KB) - } - return fmt.Sprintf("%.2fB", b) -} - -func main() { - fmt.Println(YB, ByteSize(1e13)) -} diff --git a/doc/progs/eff_qr.go b/doc/progs/eff_qr.go deleted file mode 100644 index f2055f08c3..0000000000 --- a/doc/progs/eff_qr.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import ( - "flag" - "html/template" - "log" - "net/http" -) - -var addr = flag.String("addr", ":1718", "http service address") // Q=17, R=18 - -var templ = template.Must(template.New("qr").Parse(templateStr)) - -func main() { - flag.Parse() - http.Handle("/", http.HandlerFunc(QR)) - err := http.ListenAndServe(*addr, nil) - if err != nil { - log.Fatal("ListenAndServe:", err) - } -} - -func QR(w http.ResponseWriter, req *http.Request) { - templ.Execute(w, req.FormValue("s")) -} - -const templateStr = ` - - -QR Link Generator - - -{{if .}} - -
-{{.}} -
-
-{{end}} -
- - -
- - -` diff --git a/doc/progs/eff_sequence.go b/doc/progs/eff_sequence.go deleted file mode 100644 index ab1826b6ee..0000000000 --- a/doc/progs/eff_sequence.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import ( - "fmt" - "sort" -) - -func main() { - seq := Sequence{6, 2, -1, 44, 16} - sort.Sort(seq) - fmt.Println(seq) -} - -type Sequence []int - -// Methods required by sort.Interface. -func (s Sequence) Len() int { - return len(s) -} -func (s Sequence) Less(i, j int) bool { - return s[i] < s[j] -} -func (s Sequence) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} - -// Copy returns a copy of the Sequence. -func (s Sequence) Copy() Sequence { - copy := make(Sequence, 0, len(s)) - return append(copy, s...) -} - -// Method for printing - sorts the elements before printing. -func (s Sequence) String() string { - s = s.Copy() // Make a copy; don't overwrite argument. - sort.Sort(s) - str := "[" - for i, elem := range s { // Loop is O(N²); will fix that in next example. - if i > 0 { - str += " " - } - str += fmt.Sprint(elem) - } - return str + "]" -} diff --git a/doc/progs/eff_unused1.go b/doc/progs/eff_unused1.go deleted file mode 100644 index 285d55eee5..0000000000 --- a/doc/progs/eff_unused1.go +++ /dev/null @@ -1,16 +0,0 @@ -package main - -import ( - "fmt" - "io" - "log" - "os" -) - -func main() { - fd, err := os.Open("test.go") - if err != nil { - log.Fatal(err) - } - // TODO: use fd. -} diff --git a/doc/progs/eff_unused2.go b/doc/progs/eff_unused2.go deleted file mode 100644 index 92eb74e053..0000000000 --- a/doc/progs/eff_unused2.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import ( - "fmt" - "io" - "log" - "os" -) - -var _ = fmt.Printf // For debugging; delete when done. -var _ io.Reader // For debugging; delete when done. - -func main() { - fd, err := os.Open("test.go") - if err != nil { - log.Fatal(err) - } - // TODO: use fd. - _ = fd -} diff --git a/doc/progs/error.go b/doc/progs/error.go deleted file mode 100644 index e776cdba17..0000000000 --- a/doc/progs/error.go +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file contains the code snippets included in "Error Handling and Go." - -package main - -import ( - "encoding/json" - "errors" - "fmt" - "log" - "net" - "os" - "time" -) - -type File struct{} - -func Open(name string) (file *File, err error) { - // OMIT - panic(1) - // STOP OMIT -} - -func openFile() { // OMIT - f, err := os.Open("filename.ext") - if err != nil { - log.Fatal(err) - } - // do something with the open *File f - // STOP OMIT - _ = f -} - -// errorString is a trivial implementation of error. -type errorString struct { - s string -} - -func (e *errorString) Error() string { - return e.s -} - -// STOP OMIT - -// New returns an error that formats as the given text. -func New(text string) error { - return &errorString{text} -} - -// STOP OMIT - -func Sqrt(f float64) (float64, error) { - if f < 0 { - return 0, errors.New("math: square root of negative number") - } - // implementation - return 0, nil // OMIT -} - -// STOP OMIT - -func printErr() (int, error) { // OMIT - f, err := Sqrt(-1) - if err != nil { - fmt.Println(err) - } - // STOP OMIT - // fmtError OMIT - if f < 0 { - return 0, fmt.Errorf("math: square root of negative number %g", f) - } - // STOP OMIT - return 0, nil -} - -type NegativeSqrtError float64 - -func (f NegativeSqrtError) Error() string { - return fmt.Sprintf("math: square root of negative number %g", float64(f)) -} - -// STOP OMIT - -type SyntaxError struct { - msg string // description of error - Offset int64 // error occurred after reading Offset bytes -} - -func (e *SyntaxError) Error() string { return e.msg } - -// STOP OMIT - -func decodeError(dec *json.Decoder, val struct{}) error { // OMIT - var f os.FileInfo // OMIT - if err := dec.Decode(&val); err != nil { - if serr, ok := err.(*json.SyntaxError); ok { - line, col := findLine(f, serr.Offset) - return fmt.Errorf("%s:%d:%d: %v", f.Name(), line, col, err) - } - return err - } - // STOP OMIT - return nil -} - -func findLine(os.FileInfo, int64) (int, int) { - // place holder; no need to run - return 0, 0 -} - -func netError(err error) { // OMIT - for { // OMIT - if nerr, ok := err.(net.Error); ok && nerr.Temporary() { - time.Sleep(1e9) - continue - } - if err != nil { - log.Fatal(err) - } - // STOP OMIT - } -} - -func main() {} diff --git a/doc/progs/error2.go b/doc/progs/error2.go deleted file mode 100644 index 086b6710d3..0000000000 --- a/doc/progs/error2.go +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file contains the code snippets included in "Error Handling and Go." - -package main - -import ( - "net/http" - "text/template" -) - -func init() { - http.HandleFunc("/view", viewRecord) -} - -func viewRecord(w http.ResponseWriter, r *http.Request) { - c := appengine.NewContext(r) - key := datastore.NewKey(c, "Record", r.FormValue("id"), 0, nil) - record := new(Record) - if err := datastore.Get(c, key, record); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - if err := viewTemplate.Execute(w, record); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } -} - -// STOP OMIT - -type ap struct{} - -func (ap) NewContext(*http.Request) *ctx { return nil } - -type ctx struct{} - -func (*ctx) Errorf(string, ...interface{}) {} - -var appengine ap - -type ds struct{} - -func (ds) NewKey(*ctx, string, string, int, *int) string { return "" } -func (ds) Get(*ctx, string, *Record) error { return nil } - -var datastore ds - -type Record struct{} - -var viewTemplate *template.Template - -func main() {} diff --git a/doc/progs/error3.go b/doc/progs/error3.go deleted file mode 100644 index d9e56b5d64..0000000000 --- a/doc/progs/error3.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file contains the code snippets included in "Error Handling and Go." - -package main - -import ( - "net/http" - "text/template" -) - -func init() { - http.Handle("/view", appHandler(viewRecord)) -} - -// STOP OMIT - -func viewRecord(w http.ResponseWriter, r *http.Request) error { - c := appengine.NewContext(r) - key := datastore.NewKey(c, "Record", r.FormValue("id"), 0, nil) - record := new(Record) - if err := datastore.Get(c, key, record); err != nil { - return err - } - return viewTemplate.Execute(w, record) -} - -// STOP OMIT - -type appHandler func(http.ResponseWriter, *http.Request) error - -func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - if err := fn(w, r); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - } -} - -// STOP OMIT - -type ap struct{} - -func (ap) NewContext(*http.Request) *ctx { return nil } - -type ctx struct{} - -func (*ctx) Errorf(string, ...interface{}) {} - -var appengine ap - -type ds struct{} - -func (ds) NewKey(*ctx, string, string, int, *int) string { return "" } -func (ds) Get(*ctx, string, *Record) error { return nil } - -var datastore ds - -type Record struct{} - -var viewTemplate *template.Template - -func main() {} diff --git a/doc/progs/error4.go b/doc/progs/error4.go deleted file mode 100644 index 8b2f3049de..0000000000 --- a/doc/progs/error4.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file contains the code snippets included in "Error Handling and Go." - -package main - -import ( - "net/http" - "text/template" -) - -type appError struct { - Error error - Message string - Code int -} - -// STOP OMIT - -type appHandler func(http.ResponseWriter, *http.Request) *appError - -func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - if e := fn(w, r); e != nil { // e is *appError, not error. - c := appengine.NewContext(r) - c.Errorf("%v", e.Error) - http.Error(w, e.Message, e.Code) - } -} - -// STOP OMIT - -func viewRecord(w http.ResponseWriter, r *http.Request) *appError { - c := appengine.NewContext(r) - key := datastore.NewKey(c, "Record", r.FormValue("id"), 0, nil) - record := new(Record) - if err := datastore.Get(c, key, record); err != nil { - return &appError{err, "Record not found", 404} - } - if err := viewTemplate.Execute(w, record); err != nil { - return &appError{err, "Can't display record", 500} - } - return nil -} - -// STOP OMIT - -func init() { - http.Handle("/view", appHandler(viewRecord)) -} - -type ap struct{} - -func (ap) NewContext(*http.Request) *ctx { return nil } - -type ctx struct{} - -func (*ctx) Errorf(string, ...interface{}) {} - -var appengine ap - -type ds struct{} - -func (ds) NewKey(*ctx, string, string, int, *int) string { return "" } -func (ds) Get(*ctx, string, *Record) error { return nil } - -var datastore ds - -type Record struct{} - -var viewTemplate *template.Template - -func main() {} diff --git a/doc/progs/go1.go b/doc/progs/go1.go deleted file mode 100644 index 50fd93441f..0000000000 --- a/doc/progs/go1.go +++ /dev/null @@ -1,245 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file contains examples to embed in the Go 1 release notes document. - -package main - -import ( - "errors" - "flag" - "fmt" - "log" - "os" - "path/filepath" - "testing" - "time" - "unicode" -) - -func main() { - flag.Parse() - stringAppend() - mapDelete() - mapIteration() - multipleAssignment() - structEquality() - compositeLiterals() - runeType() - errorExample() - timePackage() - walkExample() - osIsExist() -} - -var timeout = flag.Duration("timeout", 30*time.Second, "how long to wait for completion") - -func init() { - // canonicalize the logging - log.SetFlags(0) -} - -func mapDelete() { - m := map[string]int{"7": 7, "23": 23} - k := "7" - delete(m, k) - if m["7"] != 0 || m["23"] != 23 { - log.Fatal("mapDelete:", m) - } -} - -func stringAppend() { - greeting := []byte{} - greeting = append(greeting, []byte("hello ")...) - greeting = append(greeting, "world"...) - if string(greeting) != "hello world" { - log.Fatal("stringAppend: ", string(greeting)) - } -} - -func mapIteration() { - m := map[string]int{"Sunday": 0, "Monday": 1} - for name, value := range m { - // This loop should not assume Sunday will be visited first. - f(name, value) - } -} - -func f(string, int) { -} - -func assert(t bool) { - if !t { - log.Panic("assertion fail") - } -} - -func multipleAssignment() { - sa := []int{1, 2, 3} - i := 0 - i, sa[i] = 1, 2 // sets i = 1, sa[0] = 2 - - sb := []int{1, 2, 3} - j := 0 - sb[j], j = 2, 1 // sets sb[0] = 2, j = 1 - - sc := []int{1, 2, 3} - sc[0], sc[0] = 1, 2 // sets sc[0] = 1, then sc[0] = 2 (so sc[0] = 2 at end) - - assert(i == 1 && sa[0] == 2) - assert(j == 1 && sb[0] == 2) - assert(sc[0] == 2) -} - -func structEquality() { - type Day struct { - long string - short string - } - Christmas := Day{"Christmas", "XMas"} - Thanksgiving := Day{"Thanksgiving", "Turkey"} - holiday := map[Day]bool{ - Christmas: true, - Thanksgiving: true, - } - fmt.Printf("Christmas is a holiday: %t\n", holiday[Christmas]) -} - -func compositeLiterals() { - type Date struct { - month string - day int - } - // Struct values, fully qualified; always legal. - holiday1 := []Date{ - Date{"Feb", 14}, - Date{"Nov", 11}, - Date{"Dec", 25}, - } - // Struct values, type name elided; always legal. - holiday2 := []Date{ - {"Feb", 14}, - {"Nov", 11}, - {"Dec", 25}, - } - // Pointers, fully qualified, always legal. - holiday3 := []*Date{ - &Date{"Feb", 14}, - &Date{"Nov", 11}, - &Date{"Dec", 25}, - } - // Pointers, type name elided; legal in Go 1. - holiday4 := []*Date{ - {"Feb", 14}, - {"Nov", 11}, - {"Dec", 25}, - } - // STOP OMIT - _, _, _, _ = holiday1, holiday2, holiday3, holiday4 -} - -func runeType() { - // STARTRUNE OMIT - delta := 'δ' // delta has type rune. - var DELTA rune - DELTA = unicode.ToUpper(delta) - epsilon := unicode.ToLower(DELTA + 1) - if epsilon != 'δ'+1 { - log.Fatal("inconsistent casing for Greek") - } - // ENDRUNE OMIT -} - -// START ERROR EXAMPLE OMIT -type SyntaxError struct { - File string - Line int - Message string -} - -func (se *SyntaxError) Error() string { - return fmt.Sprintf("%s:%d: %s", se.File, se.Line, se.Message) -} - -// END ERROR EXAMPLE OMIT - -func errorExample() { - var ErrSyntax = errors.New("syntax error") - _ = ErrSyntax - se := &SyntaxError{"file", 7, "error"} - got := fmt.Sprint(se) - const expect = "file:7: error" - if got != expect { - log.Fatalf("errorsPackage: expected %q got %q", expect, got) - } -} - -// sleepUntil sleeps until the specified time. It returns immediately if it's too late. -func sleepUntil(wakeup time.Time) { - now := time.Now() // A Time. - if !wakeup.After(now) { - return - } - delta := wakeup.Sub(now) // A Duration. - fmt.Printf("Sleeping for %.3fs\n", delta.Seconds()) - time.Sleep(delta) -} - -func timePackage() { - sleepUntil(time.Now().Add(123 * time.Millisecond)) -} - -func walkExample() { - // STARTWALK OMIT - markFn := func(path string, info os.FileInfo, err error) error { - if path == "pictures" { // Will skip walking of directory pictures and its contents. - return filepath.SkipDir - } - if err != nil { - return err - } - log.Println(path) - return nil - } - err := filepath.Walk(".", markFn) - if err != nil { - log.Fatal(err) - } - // ENDWALK OMIT -} - -func initializationFunction(c chan int) { - c <- 1 -} - -var PackageGlobal int - -func init() { - c := make(chan int) - go initializationFunction(c) - PackageGlobal = <-c -} - -func BenchmarkSprintf(b *testing.B) { - // Verify correctness before running benchmark. - b.StopTimer() - got := fmt.Sprintf("%x", 23) - const expect = "17" - if expect != got { - b.Fatalf("expected %q; got %q", expect, got) - } - b.StartTimer() - for i := 0; i < b.N; i++ { - fmt.Sprintf("%x", 23) - } -} - -func osIsExist() { - name := "go1.go" - f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) - if os.IsExist(err) { - log.Printf("%s already exists", name) - } - _ = f -} diff --git a/doc/progs/gobs1.go b/doc/progs/gobs1.go deleted file mode 100644 index 7077ca159f..0000000000 --- a/doc/progs/gobs1.go +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gobs1 - -type T struct{ X, Y, Z int } // Only exported fields are encoded and decoded. -var t = T{X: 7, Y: 0, Z: 8} - -// STOP OMIT - -type U struct{ X, Y *int8 } // Note: pointers to int8s -var u U - -// STOP OMIT - -type Node struct { - Value int - Left, Right *Node -} - -// STOP OMIT diff --git a/doc/progs/gobs2.go b/doc/progs/gobs2.go deleted file mode 100644 index 85bb41cdca..0000000000 --- a/doc/progs/gobs2.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import ( - "bytes" - "encoding/gob" - "fmt" - "log" -) - -type P struct { - X, Y, Z int - Name string -} - -type Q struct { - X, Y *int32 - Name string -} - -func main() { - // Initialize the encoder and decoder. Normally enc and dec would be - // bound to network connections and the encoder and decoder would - // run in different processes. - var network bytes.Buffer // Stand-in for a network connection - enc := gob.NewEncoder(&network) // Will write to network. - dec := gob.NewDecoder(&network) // Will read from network. - // Encode (send) the value. - err := enc.Encode(P{3, 4, 5, "Pythagoras"}) - if err != nil { - log.Fatal("encode error:", err) - } - // Decode (receive) the value. - var q Q - err = dec.Decode(&q) - if err != nil { - log.Fatal("decode error:", err) - } - fmt.Printf("%q: {%d,%d}\n", q.Name, *q.X, *q.Y) -} diff --git a/doc/progs/image_draw.go b/doc/progs/image_draw.go deleted file mode 100644 index bb73c8a714..0000000000 --- a/doc/progs/image_draw.go +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file contains the code snippets included in "The Go image/draw package." - -package main - -import ( - "image" - "image/color" - "image/draw" -) - -func main() { - Color() - Rect() - RectAndScroll() - ConvAndCircle() - Glyph() -} - -func Color() { - c := color.RGBA{255, 0, 255, 255} - r := image.Rect(0, 0, 640, 480) - dst := image.NewRGBA(r) - - // ZERO OMIT - // image.ZP is the zero point -- the origin. - draw.Draw(dst, r, &image.Uniform{c}, image.ZP, draw.Src) - // STOP OMIT - - // BLUE OMIT - m := image.NewRGBA(image.Rect(0, 0, 640, 480)) - blue := color.RGBA{0, 0, 255, 255} - draw.Draw(m, m.Bounds(), &image.Uniform{blue}, image.ZP, draw.Src) - // STOP OMIT - - // RESET OMIT - draw.Draw(m, m.Bounds(), image.Transparent, image.ZP, draw.Src) - // STOP OMIT -} - -func Rect() { - dst := image.NewRGBA(image.Rect(0, 0, 640, 480)) - sr := image.Rect(0, 0, 200, 200) - src := image.Black - dp := image.Point{100, 100} - - // RECT OMIT - r := image.Rectangle{dp, dp.Add(sr.Size())} - draw.Draw(dst, r, src, sr.Min, draw.Src) - // STOP OMIT -} - -func RectAndScroll() { - dst := image.NewRGBA(image.Rect(0, 0, 640, 480)) - sr := image.Rect(0, 0, 200, 200) - src := image.Black - dp := image.Point{100, 100} - - // RECT2 OMIT - r := sr.Sub(sr.Min).Add(dp) - draw.Draw(dst, r, src, sr.Min, draw.Src) - // STOP OMIT - - m := dst - - // SCROLL OMIT - b := m.Bounds() - p := image.Pt(0, 20) - // Note that even though the second argument is b, - // the effective rectangle is smaller due to clipping. - draw.Draw(m, b, m, b.Min.Add(p), draw.Src) - dirtyRect := b.Intersect(image.Rect(b.Min.X, b.Max.Y-20, b.Max.X, b.Max.Y)) - // STOP OMIT - - _ = dirtyRect // noop -} - -func ConvAndCircle() { - src := image.NewRGBA(image.Rect(0, 0, 640, 480)) - dst := image.NewRGBA(image.Rect(0, 0, 640, 480)) - - // CONV OMIT - b := src.Bounds() - m := image.NewRGBA(b) - draw.Draw(m, b, src, b.Min, draw.Src) - // STOP OMIT - - p := image.Point{100, 100} - r := 50 - - // CIRCLE2 OMIT - draw.DrawMask(dst, dst.Bounds(), src, image.ZP, &circle{p, r}, image.ZP, draw.Over) - // STOP OMIT -} - -func theGlyphImageForAFont() image.Image { - return image.NewRGBA(image.Rect(0, 0, 640, 480)) -} - -func theBoundsFor(index int) image.Rectangle { - return image.Rect(0, 0, 32, 32) -} - -func Glyph() { - p := image.Point{100, 100} - dst := image.NewRGBA(image.Rect(0, 0, 640, 480)) - glyphIndex := 42 - - // GLYPH OMIT - src := &image.Uniform{color.RGBA{0, 0, 255, 255}} - mask := theGlyphImageForAFont() - mr := theBoundsFor(glyphIndex) - draw.DrawMask(dst, mr.Sub(mr.Min).Add(p), src, image.ZP, mask, mr.Min, draw.Over) - // STOP OMIT -} - -//CIRCLESTRUCT OMIT -type circle struct { - p image.Point - r int -} - -func (c *circle) ColorModel() color.Model { - return color.AlphaModel -} - -func (c *circle) Bounds() image.Rectangle { - return image.Rect(c.p.X-c.r, c.p.Y-c.r, c.p.X+c.r, c.p.Y+c.r) -} - -func (c *circle) At(x, y int) color.Color { - xx, yy, rr := float64(x-c.p.X)+0.5, float64(y-c.p.Y)+0.5, float64(c.r) - if xx*xx+yy*yy < rr*rr { - return color.Alpha{255} - } - return color.Alpha{0} -} - -//STOP OMIT diff --git a/doc/progs/image_package1.go b/doc/progs/image_package1.go deleted file mode 100644 index c4c401e729..0000000000 --- a/doc/progs/image_package1.go +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import ( - "fmt" - "image" -) - -func main() { - p := image.Point{2, 1} - fmt.Println("X is", p.X, "Y is", p.Y) -} diff --git a/doc/progs/image_package2.go b/doc/progs/image_package2.go deleted file mode 100644 index fcb5d9fd03..0000000000 --- a/doc/progs/image_package2.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import ( - "fmt" - "image" -) - -func main() { - r := image.Rect(2, 1, 5, 5) - // Dx and Dy return a rectangle's width and height. - fmt.Println(r.Dx(), r.Dy(), image.Pt(0, 0).In(r)) // prints 3 4 false -} diff --git a/doc/progs/image_package3.go b/doc/progs/image_package3.go deleted file mode 100644 index 13d0f08079..0000000000 --- a/doc/progs/image_package3.go +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import ( - "fmt" - "image" -) - -func main() { - r := image.Rect(2, 1, 5, 5).Add(image.Pt(-4, -2)) - fmt.Println(r.Dx(), r.Dy(), image.Pt(0, 0).In(r)) // prints 3 4 true -} diff --git a/doc/progs/image_package4.go b/doc/progs/image_package4.go deleted file mode 100644 index c46fddf07a..0000000000 --- a/doc/progs/image_package4.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import ( - "fmt" - "image" -) - -func main() { - r := image.Rect(0, 0, 4, 3).Intersect(image.Rect(2, 2, 5, 5)) - // Size returns a rectangle's width and height, as a Point. - fmt.Printf("%#v\n", r.Size()) // prints image.Point{X:2, Y:1} -} diff --git a/doc/progs/image_package5.go b/doc/progs/image_package5.go deleted file mode 100644 index 0bb5c7608e..0000000000 --- a/doc/progs/image_package5.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import ( - "fmt" - "image" - "image/color" -) - -func main() { - m := image.NewRGBA(image.Rect(0, 0, 640, 480)) - m.Set(5, 5, color.RGBA{255, 0, 0, 255}) - fmt.Println(m.At(5, 5)) -} diff --git a/doc/progs/image_package6.go b/doc/progs/image_package6.go deleted file mode 100644 index 62eeecdb92..0000000000 --- a/doc/progs/image_package6.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import ( - "fmt" - "image" -) - -func main() { - m0 := image.NewRGBA(image.Rect(0, 0, 8, 5)) - m1 := m0.SubImage(image.Rect(1, 2, 5, 5)).(*image.RGBA) - fmt.Println(m0.Bounds().Dx(), m1.Bounds().Dx()) // prints 8, 4 - fmt.Println(m0.Stride == m1.Stride) // prints true -} diff --git a/doc/progs/interface.go b/doc/progs/interface.go deleted file mode 100644 index c2925d590d..0000000000 --- a/doc/progs/interface.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file contains the code snippets included in "The Laws of Reflection." - -package main - -import ( - "bufio" - "bytes" - "io" - "os" -) - -type MyInt int - -var i int -var j MyInt - -// STOP OMIT - -// Reader is the interface that wraps the basic Read method. -type Reader interface { - Read(p []byte) (n int, err error) -} - -// Writer is the interface that wraps the basic Write method. -type Writer interface { - Write(p []byte) (n int, err error) -} - -// STOP OMIT - -func readers() { // OMIT - var r io.Reader - r = os.Stdin - r = bufio.NewReader(r) - r = new(bytes.Buffer) - // and so on - // STOP OMIT -} - -func typeAssertions() (interface{}, error) { // OMIT - var r io.Reader - tty, err := os.OpenFile("/dev/tty", os.O_RDWR, 0) - if err != nil { - return nil, err - } - r = tty - // STOP OMIT - var w io.Writer - w = r.(io.Writer) - // STOP OMIT - var empty interface{} - empty = w - // STOP OMIT - return empty, err -} - -func main() { -} diff --git a/doc/progs/interface2.go b/doc/progs/interface2.go deleted file mode 100644 index a541d94e48..0000000000 --- a/doc/progs/interface2.go +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file contains the code snippets included in "The Laws of Reflection." - -package main - -import ( - "fmt" - "reflect" -) - -func main() { - var x float64 = 3.4 - fmt.Println("type:", reflect.TypeOf(x)) - // STOP OMIT - // TODO(proppy): test output OMIT -} - -// STOP main OMIT - -func f1() { - // START f1 OMIT - var x float64 = 3.4 - v := reflect.ValueOf(x) - fmt.Println("type:", v.Type()) - fmt.Println("kind is float64:", v.Kind() == reflect.Float64) - fmt.Println("value:", v.Float()) - // STOP OMIT -} - -func f2() { - // START f2 OMIT - var x uint8 = 'x' - v := reflect.ValueOf(x) - fmt.Println("type:", v.Type()) // uint8. - fmt.Println("kind is uint8: ", v.Kind() == reflect.Uint8) // true. - x = uint8(v.Uint()) // v.Uint returns a uint64. - // STOP OMIT -} - -func f3() { - // START f3 OMIT - type MyInt int - var x MyInt = 7 - v := reflect.ValueOf(x) - // STOP OMIT - // START f3b OMIT - y := v.Interface().(float64) // y will have type float64. - fmt.Println(y) - // STOP OMIT - // START f3c OMIT - fmt.Println(v.Interface()) - // STOP OMIT - // START f3d OMIT - fmt.Printf("value is %7.1e\n", v.Interface()) - // STOP OMIT -} - -func f4() { - // START f4 OMIT - var x float64 = 3.4 - v := reflect.ValueOf(x) - v.SetFloat(7.1) // Error: will panic. - // STOP OMIT -} - -func f5() { - // START f5 OMIT - var x float64 = 3.4 - v := reflect.ValueOf(x) - fmt.Println("settability of v:", v.CanSet()) - // STOP OMIT -} - -func f6() { - // START f6 OMIT - var x float64 = 3.4 - v := reflect.ValueOf(x) - // STOP OMIT - // START f6b OMIT - v.SetFloat(7.1) - // STOP OMIT -} - -func f7() { - // START f7 OMIT - var x float64 = 3.4 - p := reflect.ValueOf(&x) // Note: take the address of x. - fmt.Println("type of p:", p.Type()) - fmt.Println("settability of p:", p.CanSet()) - // STOP OMIT - // START f7b OMIT - v := p.Elem() - fmt.Println("settability of v:", v.CanSet()) - // STOP OMIT - // START f7c OMIT - v.SetFloat(7.1) - fmt.Println(v.Interface()) - fmt.Println(x) - // STOP OMIT -} - -func f8() { - // START f8 OMIT - type T struct { - A int - B string - } - t := T{23, "skidoo"} - s := reflect.ValueOf(&t).Elem() - typeOfT := s.Type() - for i := 0; i < s.NumField(); i++ { - f := s.Field(i) - fmt.Printf("%d: %s %s = %v\n", i, - typeOfT.Field(i).Name, f.Type(), f.Interface()) - } - // STOP OMIT - // START f8b OMIT - s.Field(0).SetInt(77) - s.Field(1).SetString("Sunset Strip") - fmt.Println("t is now", t) - // STOP OMIT -} - -func f9() { - // START f9 OMIT - var x float64 = 3.4 - fmt.Println("value:", reflect.ValueOf(x)) - // STOP OMIT -} diff --git a/doc/progs/json1.go b/doc/progs/json1.go deleted file mode 100644 index 9804efbaae..0000000000 --- a/doc/progs/json1.go +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import ( - "encoding/json" - "log" - "reflect" -) - -type Message struct { - Name string - Body string - Time int64 -} - -// STOP OMIT - -func Encode() { - m := Message{"Alice", "Hello", 1294706395881547000} - b, err := json.Marshal(m) - - if err != nil { - panic(err) - } - - expected := []byte(`{"Name":"Alice","Body":"Hello","Time":1294706395881547000}`) - if !reflect.DeepEqual(b, expected) { - log.Panicf("Error marshaling %q, expected %q, got %q.", m, expected, b) - } - -} - -func Decode() { - b := []byte(`{"Name":"Alice","Body":"Hello","Time":1294706395881547000}`) - var m Message - err := json.Unmarshal(b, &m) - - if err != nil { - panic(err) - } - - expected := Message{ - Name: "Alice", - Body: "Hello", - Time: 1294706395881547000, - } - - if !reflect.DeepEqual(m, expected) { - log.Panicf("Error unmarshaling %q, expected %q, got %q.", b, expected, m) - } - - m = Message{ - Name: "Alice", - Body: "Hello", - Time: 1294706395881547000, - } - - // STOP OMIT -} - -func PartialDecode() { - b := []byte(`{"Name":"Bob","Food":"Pickle"}`) - var m Message - err := json.Unmarshal(b, &m) - - // STOP OMIT - - if err != nil { - panic(err) - } - - expected := Message{ - Name: "Bob", - } - - if !reflect.DeepEqual(expected, m) { - log.Panicf("Error unmarshaling %q, expected %q, got %q.", b, expected, m) - } -} - -func main() { - Encode() - Decode() - PartialDecode() -} diff --git a/doc/progs/json2.go b/doc/progs/json2.go deleted file mode 100644 index 6089ae6710..0000000000 --- a/doc/progs/json2.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import ( - "fmt" - "math" -) - -func InterfaceExample() { - var i interface{} - i = "a string" - i = 2011 - i = 2.777 - - // STOP OMIT - - r := i.(float64) - fmt.Println("the circle's area", math.Pi*r*r) - - // STOP OMIT - - switch v := i.(type) { - case int: - fmt.Println("twice i is", v*2) - case float64: - fmt.Println("the reciprocal of i is", 1/v) - case string: - h := len(v) / 2 - fmt.Println("i swapped by halves is", v[h:]+v[:h]) - default: - // i isn't one of the types above - } - - // STOP OMIT -} - -func main() { - InterfaceExample() -} diff --git a/doc/progs/json3.go b/doc/progs/json3.go deleted file mode 100644 index 442c155b08..0000000000 --- a/doc/progs/json3.go +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import ( - "encoding/json" - "fmt" - "log" - "reflect" -) - -func Decode() { - b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`) - - var f interface{} - err := json.Unmarshal(b, &f) - - // STOP OMIT - - if err != nil { - panic(err) - } - - expected := map[string]interface{}{ - "Name": "Wednesday", - "Age": float64(6), - "Parents": []interface{}{ - "Gomez", - "Morticia", - }, - } - - if !reflect.DeepEqual(f, expected) { - log.Panicf("Error unmarshaling %q, expected %q, got %q", b, expected, f) - } - - f = map[string]interface{}{ - "Name": "Wednesday", - "Age": 6, - "Parents": []interface{}{ - "Gomez", - "Morticia", - }, - } - - // STOP OMIT - - m := f.(map[string]interface{}) - - for k, v := range m { - switch vv := v.(type) { - case string: - fmt.Println(k, "is string", vv) - case int: - fmt.Println(k, "is int", vv) - case []interface{}: - fmt.Println(k, "is an array:") - for i, u := range vv { - fmt.Println(i, u) - } - default: - fmt.Println(k, "is of a type I don't know how to handle") - } - } - - // STOP OMIT -} - -func main() { - Decode() -} diff --git a/doc/progs/json4.go b/doc/progs/json4.go deleted file mode 100644 index 1c7e5b4cfa..0000000000 --- a/doc/progs/json4.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import ( - "encoding/json" - "log" - "reflect" -) - -type FamilyMember struct { - Name string - Age int - Parents []string -} - -// STOP OMIT - -func Decode() { - b := []byte(`{"Name":"Bob","Age":20,"Parents":["Morticia", "Gomez"]}`) - var m FamilyMember - err := json.Unmarshal(b, &m) - - // STOP OMIT - - if err != nil { - panic(err) - } - - expected := FamilyMember{ - Name: "Bob", - Age: 20, - Parents: []string{"Morticia", "Gomez"}, - } - - if !reflect.DeepEqual(expected, m) { - log.Panicf("Error unmarshaling %q, expected %q, got %q", b, expected, m) - } -} - -func main() { - Decode() -} diff --git a/doc/progs/json5.go b/doc/progs/json5.go deleted file mode 100644 index 6d7a4ca8c4..0000000000 --- a/doc/progs/json5.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import ( - "encoding/json" - "log" - "os" -) - -func main() { - dec := json.NewDecoder(os.Stdin) - enc := json.NewEncoder(os.Stdout) - for { - var v map[string]interface{} - if err := dec.Decode(&v); err != nil { - log.Println(err) - return - } - for k := range v { - if k != "Name" { - delete(v, k) - } - } - if err := enc.Encode(&v); err != nil { - log.Println(err) - } - } -} diff --git a/doc/progs/run.go b/doc/progs/run.go deleted file mode 100644 index 8ac75cdcff..0000000000 --- a/doc/progs/run.go +++ /dev/null @@ -1,229 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// run runs the docs tests found in this directory. -package main - -import ( - "bytes" - "flag" - "fmt" - "io/ioutil" - "os" - "os/exec" - "path/filepath" - "regexp" - "runtime" - "strings" - "time" -) - -const usage = `go run run.go [tests] - -run.go runs the docs tests in this directory. -If no tests are provided, it runs all tests. -Tests may be specified without their .go suffix. -` - -func main() { - start := time.Now() - - flag.Usage = func() { - fmt.Fprintf(os.Stderr, usage) - flag.PrintDefaults() - os.Exit(2) - } - - flag.Parse() - if flag.NArg() == 0 { - // run all tests - fixcgo() - } else { - // run specified tests - onlyTest(flag.Args()...) - } - - tmpdir, err := ioutil.TempDir("", "go-progs") - if err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } - - // ratec limits the number of tests running concurrently. - // None of the tests are intensive, so don't bother - // trying to manually adjust for slow builders. - ratec := make(chan bool, runtime.NumCPU()) - errc := make(chan error, len(tests)) - - for _, tt := range tests { - tt := tt - ratec <- true - go func() { - errc <- test(tmpdir, tt.file, tt.want) - <-ratec - }() - } - - var rc int - for range tests { - if err := <-errc; err != nil { - fmt.Fprintln(os.Stderr, err) - rc = 1 - } - } - os.Remove(tmpdir) - if rc == 0 { - fmt.Printf("ok\t%s\t%s\n", filepath.Base(os.Args[0]), time.Since(start).Round(time.Millisecond)) - } - os.Exit(rc) -} - -// test builds the test in the given file. -// If want is non-empty, test also runs the test -// and checks that the output matches the regexp want. -func test(tmpdir, file, want string) error { - // Build the program. - prog := filepath.Join(tmpdir, file+".exe") - cmd := exec.Command("go", "build", "-o", prog, file+".go") - out, err := cmd.CombinedOutput() - if err != nil { - return fmt.Errorf("go build %s.go failed: %v\nOutput:\n%s", file, err, out) - } - defer os.Remove(prog) - - // Only run the test if we have output to check. - if want == "" { - return nil - } - - cmd = exec.Command(prog) - out, err = cmd.CombinedOutput() - if err != nil { - return fmt.Errorf("%s failed: %v\nOutput:\n%s", file, err, out) - } - - // Canonicalize output. - out = bytes.TrimRight(out, "\n") - out = bytes.ReplaceAll(out, []byte{'\n'}, []byte{' '}) - - // Check the result. - match, err := regexp.Match(want, out) - if err != nil { - return fmt.Errorf("failed to parse regexp %q: %v", want, err) - } - if !match { - return fmt.Errorf("%s.go:\n%q\ndoes not match %s", file, out, want) - } - - return nil -} - -type testcase struct { - file string - want string -} - -var tests = []testcase{ - // defer_panic_recover - {"defer", `^0 3210 2$`}, - {"defer2", `^Calling g. Printing in g 0 Printing in g 1 Printing in g 2 Printing in g 3 Panicking! Defer in g 3 Defer in g 2 Defer in g 1 Defer in g 0 Recovered in f 4 Returned normally from f.$`}, - - // effective_go - {"eff_bytesize", `^1.00YB 9.09TB$`}, - {"eff_qr", ""}, - {"eff_sequence", `^\[-1 2 6 16 44\]$`}, - {"eff_unused2", ""}, - - // error_handling - {"error", ""}, - {"error2", ""}, - {"error3", ""}, - {"error4", ""}, - - // law_of_reflection - {"interface", ""}, - {"interface2", `^type: float64$`}, - - // c_go_cgo - {"cgo1", ""}, - {"cgo2", ""}, - {"cgo3", ""}, - {"cgo4", ""}, - - // timeout - {"timeout1", ""}, - {"timeout2", ""}, - - // gobs - {"gobs1", ""}, - {"gobs2", ""}, - - // json - {"json1", `^$`}, - {"json2", `the reciprocal of i is`}, - {"json3", `Age is int 6`}, - {"json4", `^$`}, - {"json5", ""}, - - // image_package - {"image_package1", `^X is 2 Y is 1$`}, - {"image_package2", `^3 4 false$`}, - {"image_package3", `^3 4 true$`}, - {"image_package4", `^image.Point{X:2, Y:1}$`}, - {"image_package5", `^{255 0 0 255}$`}, - {"image_package6", `^8 4 true$`}, - - // other - {"go1", `^Christmas is a holiday: true .*go1.go already exists$`}, - {"slices", ""}, -} - -func onlyTest(files ...string) { - var new []testcase -NextFile: - for _, file := range files { - file = strings.TrimSuffix(file, ".go") - for _, tt := range tests { - if tt.file == file { - new = append(new, tt) - continue NextFile - } - } - fmt.Fprintf(os.Stderr, "test %s.go not found\n", file) - os.Exit(1) - } - tests = new -} - -func skipTest(file string) { - for i, tt := range tests { - if tt.file == file { - copy(tests[i:], tests[i+1:]) - tests = tests[:len(tests)-1] - return - } - } - panic("delete(" + file + "): not found") -} - -func fixcgo() { - if os.Getenv("CGO_ENABLED") != "1" { - skipTest("cgo1") - skipTest("cgo2") - skipTest("cgo3") - skipTest("cgo4") - return - } - - switch runtime.GOOS { - case "freebsd": - // cgo1 and cgo2 don't run on freebsd, srandom has a different signature - skipTest("cgo1") - skipTest("cgo2") - case "netbsd": - // cgo1 and cgo2 don't run on netbsd, srandom has a different signature - skipTest("cgo1") - skipTest("cgo2") - } -} diff --git a/doc/progs/slices.go b/doc/progs/slices.go deleted file mode 100644 index 967a3e76bd..0000000000 --- a/doc/progs/slices.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package main - -import ( - "io/ioutil" - "regexp" -) - -func AppendByte(slice []byte, data ...byte) []byte { - m := len(slice) - n := m + len(data) - if n > cap(slice) { // if necessary, reallocate - // allocate double what's needed, for future growth. - newSlice := make([]byte, (n+1)*2) - copy(newSlice, slice) - slice = newSlice - } - slice = slice[0:n] - copy(slice[m:n], data) - return slice -} - -// STOP OMIT - -// Filter returns a new slice holding only -// the elements of s that satisfy fn. -func Filter(s []int, fn func(int) bool) []int { - var p []int // == nil - for _, i := range s { - if fn(i) { - p = append(p, i) - } - } - return p -} - -// STOP OMIT - -var digitRegexp = regexp.MustCompile("[0-9]+") - -func FindDigits(filename string) []byte { - b, _ := ioutil.ReadFile(filename) - return digitRegexp.Find(b) -} - -// STOP OMIT - -func CopyDigits(filename string) []byte { - b, _ := ioutil.ReadFile(filename) - b = digitRegexp.Find(b) - c := make([]byte, len(b)) - copy(c, b) - return c -} - -// STOP OMIT - -func main() { - // place holder; no need to run -} diff --git a/doc/progs/timeout1.go b/doc/progs/timeout1.go deleted file mode 100644 index 353ba6908e..0000000000 --- a/doc/progs/timeout1.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package timeout - -import ( - "time" -) - -func Timeout() { - ch := make(chan bool, 1) - timeout := make(chan bool, 1) - go func() { - time.Sleep(1 * time.Second) - timeout <- true - }() - - // STOP OMIT - - select { - case <-ch: - // a read from ch has occurred - case <-timeout: - // the read from ch has timed out - } - - // STOP OMIT -} diff --git a/doc/progs/timeout2.go b/doc/progs/timeout2.go deleted file mode 100644 index b0d34eabf8..0000000000 --- a/doc/progs/timeout2.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package query - -type Conn string - -func (c Conn) DoQuery(query string) Result { - return Result("result") -} - -type Result string - -func Query(conns []Conn, query string) Result { - ch := make(chan Result, 1) - for _, conn := range conns { - go func(c Conn) { - select { - case ch <- c.DoQuery(query): - default: - } - }(conn) - } - return <-ch -} - -// STOP OMIT diff --git a/doc/share.png b/doc/share.png deleted file mode 100644 index c04f0c71aa..0000000000 Binary files a/doc/share.png and /dev/null differ diff --git a/doc/tos.html b/doc/tos.html deleted file mode 100644 index fff46428ec..0000000000 --- a/doc/tos.html +++ /dev/null @@ -1,11 +0,0 @@ - - -

-The Go website (the "Website") is hosted by Google. -By using and/or visiting the Website, you consent to be bound by Google's general -Terms of Service -and Google's general -Privacy Policy. -

diff --git a/src/cmd/dist/test.go b/src/cmd/dist/test.go index 955ce2a063..4f081c9f88 100644 --- a/src/cmd/dist/test.go +++ b/src/cmd/dist/test.go @@ -727,14 +727,6 @@ func (t *tester) registerTests() { } } - // Doc tests only run on builders. - // They find problems approximately never. - if goos != "js" && goos != "android" && !t.iOS() && os.Getenv("GO_BUILDER_NAME") != "" { - t.registerTest("doc_progs", "../doc/progs", "go", "run", "run.go") - t.registerTest("wiki", "../doc/articles/wiki", t.goTest(), ".") - t.registerTest("codewalk", "../doc/codewalk", t.goTest(), "codewalk_test.go") - } - if goos != "android" && !t.iOS() { // There are no tests in this directory, only benchmarks. // Check that the test binary builds but don't bother running it. -- cgit v1.2.3-54-g00ecf From f0d23c9dbb2142b975fa8fb13a57213d0c15bdd1 Mon Sep 17 00:00:00 2001 From: Wei Fu Date: Sun, 24 Jan 2021 18:21:06 +0800 Subject: internal/poll: netpollcheckerr before sendfile In net/http package, the ServeContent/ServeFile doesn't check the I/O timeout error from chunkWriter or *net.TCPConn, which means that both HTTP status and headers might be missing when WriteTimeout happens. If the poll.SendFile() doesn't check the *poll.FD state before sending data, the client will only receive the response body with status and report "malformed http response/status code". This patch is to enable netpollcheckerr before sendfile, which should align with normal *poll.FD.Write() and Splice(). Fixes #43822 Change-Id: I32517e3f261bab883a58b577b813ef189214b954 Reviewed-on: https://go-review.googlesource.com/c/go/+/285914 Reviewed-by: Emmanuel Odeke Trust: Emmanuel Odeke Trust: Bryan C. Mills Run-TryBot: Emmanuel Odeke --- src/internal/poll/sendfile_bsd.go | 4 +++ src/internal/poll/sendfile_linux.go | 3 ++ src/internal/poll/sendfile_solaris.go | 3 ++ src/net/sendfile_test.go | 65 +++++++++++++++++++++++++++++++++++ 4 files changed, 75 insertions(+) diff --git a/src/internal/poll/sendfile_bsd.go b/src/internal/poll/sendfile_bsd.go index a24e41dcaa..66005a9f5c 100644 --- a/src/internal/poll/sendfile_bsd.go +++ b/src/internal/poll/sendfile_bsd.go @@ -18,6 +18,10 @@ func SendFile(dstFD *FD, src int, pos, remain int64) (int64, error) { return 0, err } defer dstFD.writeUnlock() + if err := dstFD.pd.prepareWrite(dstFD.isFile); err != nil { + return 0, err + } + dst := int(dstFD.Sysfd) var written int64 var err error diff --git a/src/internal/poll/sendfile_linux.go b/src/internal/poll/sendfile_linux.go index d64283007d..d6442e8666 100644 --- a/src/internal/poll/sendfile_linux.go +++ b/src/internal/poll/sendfile_linux.go @@ -16,6 +16,9 @@ func SendFile(dstFD *FD, src int, remain int64) (int64, error) { return 0, err } defer dstFD.writeUnlock() + if err := dstFD.pd.prepareWrite(dstFD.isFile); err != nil { + return 0, err + } dst := int(dstFD.Sysfd) var written int64 diff --git a/src/internal/poll/sendfile_solaris.go b/src/internal/poll/sendfile_solaris.go index 762992e9eb..748c85131e 100644 --- a/src/internal/poll/sendfile_solaris.go +++ b/src/internal/poll/sendfile_solaris.go @@ -20,6 +20,9 @@ func SendFile(dstFD *FD, src int, pos, remain int64) (int64, error) { return 0, err } defer dstFD.writeUnlock() + if err := dstFD.pd.prepareWrite(dstFD.isFile); err != nil { + return 0, err + } dst := int(dstFD.Sysfd) var written int64 diff --git a/src/net/sendfile_test.go b/src/net/sendfile_test.go index 657a36599f..d6057fd839 100644 --- a/src/net/sendfile_test.go +++ b/src/net/sendfile_test.go @@ -10,8 +10,10 @@ import ( "bytes" "crypto/sha256" "encoding/hex" + "errors" "fmt" "io" + "io/ioutil" "os" "runtime" "sync" @@ -313,3 +315,66 @@ func TestSendfilePipe(t *testing.T) { wg.Wait() } + +// Issue 43822: tests that returns EOF when conn write timeout. +func TestSendfileOnWriteTimeoutExceeded(t *testing.T) { + ln, err := newLocalListener("tcp") + if err != nil { + t.Fatal(err) + } + defer ln.Close() + + errc := make(chan error, 1) + go func(ln Listener) (retErr error) { + defer func() { + errc <- retErr + close(errc) + }() + + conn, err := ln.Accept() + if err != nil { + return err + } + defer conn.Close() + + // Set the write deadline in the past(1h ago). It makes + // sure that it is always write timeout. + if err := conn.SetWriteDeadline(time.Now().Add(-1 * time.Hour)); err != nil { + return err + } + + f, err := os.Open(newton) + if err != nil { + return err + } + defer f.Close() + + _, err = io.Copy(conn, f) + if errors.Is(err, os.ErrDeadlineExceeded) { + return nil + } + + if err == nil { + err = fmt.Errorf("expected ErrDeadlineExceeded, but got nil") + } + return err + }(ln) + + conn, err := Dial("tcp", ln.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + + n, err := io.Copy(ioutil.Discard, conn) + if err != nil { + t.Fatalf("expected nil error, but got %v", err) + } + if n != 0 { + t.Fatalf("expected receive zero, but got %d byte(s)", n) + } + + if err := <-errc; err != nil { + t.Fatal(err) + } +} -- cgit v1.2.3-54-g00ecf From 353e111455d6b81fdce0a6d3190baba6adca3372 Mon Sep 17 00:00:00 2001 From: KimMachineGun Date: Tue, 16 Feb 2021 15:51:32 +0000 Subject: doc/go1.16: fix mismatched id attribute For #40700. Change-Id: I186a21899404bfb79c08bfa8623caf9da74b6b0d GitHub-Last-Rev: 25d240db3c0e2a923720bb9667ef0599ec06819e GitHub-Pull-Request: golang/go#44145 Reviewed-on: https://go-review.googlesource.com/c/go/+/290329 Trust: Ian Lance Taylor Reviewed-by: Dmitri Shuralyov --- doc/go1.16.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/go1.16.html b/doc/go1.16.html index d5de0ee5ce..08f5d5431e 100644 --- a/doc/go1.16.html +++ b/doc/go1.16.html @@ -317,7 +317,7 @@ Do not send CLs removing the interior tags from such phrases.

Vet

-

New warning for invalid testing.T use in +

New warning for invalid testing.T use in goroutines

-- cgit v1.2.3-54-g00ecf From 6530f2617f3100d8f1036afc5cb9b30b36628aaa Mon Sep 17 00:00:00 2001 From: Dmitri Shuralyov Date: Sat, 13 Feb 2021 02:44:11 +0000 Subject: doc/go1.16: remove draft notice Fixes #40700. Change-Id: I99ed479d1bb3cdf469c0209720c728276182a7a9 Reviewed-on: https://go-review.googlesource.com/c/go/+/291809 Reviewed-by: Alexander Rakoczy Reviewed-by: Carlos Amedee Trust: Alexander Rakoczy Run-TryBot: Alexander Rakoczy TryBot-Result: Go Bot --- doc/go1.16.html | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/doc/go1.16.html b/doc/go1.16.html index 08f5d5431e..0beb62d160 100644 --- a/doc/go1.16.html +++ b/doc/go1.16.html @@ -14,13 +14,13 @@ Do not send CLs removing the interior tags from such phrases. main ul li { margin: 0.5em 0; } -

DRAFT RELEASE NOTES — Introduction to Go 1.16

+

Introduction to Go 1.16

- - Go 1.16 is not yet released. These are work-in-progress - release notes. Go 1.16 is expected to be released in February 2021. - + The latest Go release, version 1.16, arrives six months after Go 1.15. + Most of its changes are in the implementation of the toolchain, runtime, and libraries. + As always, the release maintains the Go 1 promise of compatibility. + We expect almost all Go programs to continue to compile and run as before.

Changes to the language

@@ -505,7 +505,7 @@ func TestFoo(t *testing.T) { On the consumer side, the new http.FS function converts an fs.FS to an - http.Handler. + http.FileSystem. Also, the html/template and text/template packages’ ParseFS @@ -952,7 +952,7 @@ func TestFoo(t *testing.T) {

The new http.FS function converts an fs.FS - to an http.Handler. + to an http.FileSystem.

-- cgit v1.2.3-54-g00ecf From 1004a7cb31ae31d2ca0b54b507b996c12403d54c Mon Sep 17 00:00:00 2001 From: Branden J Brown Date: Mon, 15 Feb 2021 23:12:15 -0500 Subject: runtime/metrics: update documentation to current interface The package documentation referenced sample metadata that was removed in CL 282632. Update this documentation to be less specific about what metadata is available. Additionally, the documentation on the Sample type referred to Descriptions instead of All as the source of metrics names. Fixes #44280. Change-Id: I24fc63a744bf498cb4cd5bda56c1599f6dd75929 Reviewed-on: https://go-review.googlesource.com/c/go/+/292309 Reviewed-by: Michael Knyszek Trust: Michael Knyszek Trust: Dmitri Shuralyov Run-TryBot: Michael Knyszek TryBot-Result: Go Bot --- src/runtime/metrics/doc.go | 4 +--- src/runtime/metrics/sample.go | 2 +- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/runtime/metrics/doc.go b/src/runtime/metrics/doc.go index 5da050f973..7f790afc12 100644 --- a/src/runtime/metrics/doc.go +++ b/src/runtime/metrics/doc.go @@ -16,9 +16,7 @@ Interface Metrics are designated by a string key, rather than, for example, a field name in a struct. The full list of supported metrics is always available in the slice of Descriptions returned by All. Each Description also includes useful information -about the metric, such as how to display it (for example, gauge vs. counter) -and how difficult or disruptive it is to obtain it (for example, do you need to -stop the world?). +about the metric. Thus, users of this API are encouraged to sample supported metrics defined by the slice returned by All to remain compatible across Go versions. Of course, situations diff --git a/src/runtime/metrics/sample.go b/src/runtime/metrics/sample.go index b3933e266e..4cf8cdf799 100644 --- a/src/runtime/metrics/sample.go +++ b/src/runtime/metrics/sample.go @@ -14,7 +14,7 @@ type Sample struct { // Name is the name of the metric sampled. // // It must correspond to a name in one of the metric descriptions - // returned by Descriptions. + // returned by All. Name string // Value is the value of the metric sample. -- cgit v1.2.3-54-g00ecf