Go语言中使用fmt.Printf的小技巧

以下摘自The Go Programming Language

When printing numbers using the fmt package, we can control the radix and format with the %d, %o, and %x verbs, as shown in this example:

o := 0666
fmt.Printf(“%d %[1]o %#[1]o\n”, o) // “438 666 0666”
x := int64(0xdeadbeef)
fmt.Printf(“%d %[1]x %#[1]x %#[1]X\n”, x)
// Output:
// 3735928559 deadbeef 0xdeadbeef 0XDEADBEEF

Note the use of two fmt tricks. Usually a Printf format string containing multiple % verbs would require the same number of extra operands, but the [1] “adverbs” after % tell Printf to use the first operand over and over again. Second, the # adverb for %o or %x or %X tells Printf to emit a 0 or 0x or 0X prefix respectively.

Rune literals are written as a character within single quotes. The simplest example is an ASCII character like ‘a’, but it’s possible to write any Unicode code point either directly or with numeric escapes, as we will see shortly.

Runes are printed with %c, or with %q if quoting is desired: ascii := ‘a’
unicode := ‘ ‘
newline := ‘\n’
fmt.Printf(“%d %[1]c %[1]q\n”, ascii) // “97 a ‘a'”
fmt.Printf(“%d %[1]c %[1]q\n”, unicode) // “22269 ‘ ‘”
fmt.Printf(“%d %[1]q\n”, newline) // “10 ‘\n'”

总结一下,“%[1]”还是格式化第一个参数;“%#”会打印出数值的前缀;而“%q”会加上引号。举例如下:

package main

import "fmt"

func main() {
    var c rune = '楠'
    fmt.Printf("%c %[1]d %#[1]x %[1]q", c)
}

执行结果:

楠 26976 0x6960 '楠'

 

Go语言的bit clear操作

以下摘自The Go Programming Language

The &^ operator is bit clear (AND NOT): in the expression z = x &^ y, each bit of z is 0 if the corresponding bit of y is 1; otherwise it equals the corresponding bit of x.

z = x &^ y运算相当于先把y取反(针对y的每个bit0变成11变成0),然后再和x进行&运算。参考下例:

package main
import "fmt"

func main(){
    var x uint8 = 1
    var y uint8 = 1 << 2

    fmt.Printf("%08b\n", x &^ y);

}  

执行结果如下:

00000001

 

Bash中的测试表达式

Bash shell中,每个执行命令都有一个返回值表示其退出状态:0表示true1表示falsetest命令是专门测试执行命令返回值,其格式如下:

test expression
或:
[ expression ]

目前test只支持3种测试对象:字符串,整数(0和正整数,不包含负数和小数点)和文件。当expression测试为“真”时,test命令就返回0true),反之返回非0false)。 关于test表达式的例子和解释,可以参考How to understand if condition in bash?

参考资料:
Shell十三问