0%

account命令

用来管理账户

list子命令

geth account list用于列出所有账户,默认数据目录是 /home/ajsoabk/.ethereum,可以通过--datadir value命令来查看特定数据目录中的账户信息,或者通过--keystore value来查看特定私钥目录中的账户信息,即:

1
root@ajsoabk-virtual-machine:/home/ajsoabk/privatechain# geth account list --datadir data

或者

1
root@ajsoabk-virtual-machine:/home/ajsoabk/privatechain# geth account list --keystore data/keystore

new子命令

创建一个新的账户并且打印账户地址,这个账户以加密的形式存储,会有提示要求设置密码

可以通过--password value参数来以非交互的形式输入密码(即从文件输入),这种方法应该只用于测试,实际使用中并不推荐,如:

1
root@ajsoabk-virtual-machine:/home/ajsoabk/privatechain# geth account new --password pwd.txt

--lightkdf参数可以用来减小密码处理过程对内存与CPU的消耗,但是会减小密码的KDF强度(即更容易被破解)

同样支持--datadir value--keystore value命令用来设置数据所在目录(默认/root/.ethereum

update子命令

geth account update <address>,用来修改账户密码,支持和new一样的参数

import子命令

从外部引入一个未加密的私钥,

attach命令

attach命令可以打开一个正在运行的节点的控制台

--jspath loadScrip参数可以改变所打开的JavaScript文件的路径(默认.

--exec value参数可以执行value(JavaScript语句)

--preload value参数可以将一系列逗号分隔的JS文件预加载入控制台

--datadir value参数可以将数据库的路径改成value(默认/home/ajsoabk/.ethereum

geth consolegeth attach都可以打开一个JavaScript并与节点交互,但是前者是启动新的节点,而后者则是通过rpc或者ipc与已经启动的节点交互。因而前者可以使用所有api,但后者只能使用已经打开的模块的api

使用geth console的时候你会发现控制台一直在输出信息,如

1
INFO [08-12|13:24:11.607] Upgrading chain index         type=bloobits percentage=88

使用命令--verbosity来调整信息详细度(0=silent,1=error,2=warn,3=info,4=debug,5=detail),默认为3

1
geth --verbosity 0 console

命令入门

基本内容

bash命令基本都是下面格式

1
$ command [ arg1 ... [ argN ]]

command是具体的命令或者一个可执行文件,arg1...argN是传递给命令或文件的参数

有些参数是命令的配置项,这些配置项一般都以一个连词线开头,比如

1
$ ls -l

同一个配置项往往有长和短两种形式,比如-l是短形式,--list是长形式,它们的作用完全相同。短形式便于手动输入,长形式一般用在脚本之中,可读性更好,利于解释自身的含义

Bash单个命令一般都是一行,用户按下回车就开始执行,有些命令比较长,写成多行有利于阅读,这时就可以在每一行结尾加上\(反斜杠),Bash就会将下一行跟当前行放在一起解释

命令组合

;可以用来在同一行中分隔不同命令,此时不管分号前的命令执行成功或失败,分号后的命令都会执行

&&||可以用于控制命令间的继发关系,如:

1
2
3
4
5
#如果command1 命令运行成功,则运行command2命令
command1 && command2

#如果command1 命令运行失败,则运行command2命令
command1 || command2

echo命令

使用echo命令输出一行文本可以不用双引号包含,如:

1
2
$ echo Hello world!
Hello world!

如果想输出多行文本,则需要用单引号或双引号包含,如:

1
2
3
4
5
6
7
8
$ echo "<HTML>
<head>
<title> Page Title</title>
</head>
<body>
Page body.
</body>
</HTML>"

echo命令输出的文本末尾会自带一个回车符,可以用-n参数取消末尾的回车符

1
2
$ echo -n a; echo b
ab

使用-e参数可以将引号中的转义字符(如\n)转义

1
2
3
4
5
$ echo "Hello\nAjsoabk!"
Hello\nAjsoabk!
$ echo -e "Hello\nAjsoabk!"
Hello
Ajsoabk!

判断内置命令

type命令用于判断某个命令是内置命令还是外部程序,如

1
2
3
4
$ type echo 
echo is a shell builtin
$ type ls
ls is hashed (/bin/ls)

如果要查看一个命令的所有定义,可以使用type命令的-a参数

1
2
3
4
5
$ type -a echo 
echo is shell builtin
echo is /usr/bin/echo
echo is /bin/echo
#说明echo既是内置命令,也有对应的外部程序

type命令的-t参数,可以返回一个命令的类型(alias别名,keyword关键词,function函数,builtin内置命令,file文件)

1
2
3
4
$ type -t bash
file
$ type -t if
keyword

快捷键

  • ctrl+l,清屏
  • ctrl+c,中止当前命令的执行
  • shift+PageUp/PageDown,向上/下滚动
  • ctrl+u /k,从光标位置删除到行首/行尾
  • ctrl+d,关闭shell对话

除了上面这些快捷键,Bash还有自动补全功能。命令输入到一半的时候,可以按下Tab键自动补全,路径也支持自动补全。如果有多个可能的选择,只需要按两次Tab,Bash会显示所有选项让你选择

注释

注释的方式有很多

  • #开头的一行会被当成注释
  • <<BLOCKBLOCK之间的内容会被当成注释
  • :''之间的内容会被当成注释

变量

变量名规则与c相同,大小写敏感

变量定义规则:

  • 变量名与值之间的=两侧都不能有空格
  • 读取或打印变量时需要使用$+变量名
  • 不需要指定数据类型,bash会自动判断数据类型

模式拓展

Shell接收到用户输入的命令以后,会根据空格将用户的输入拆分成一个个词元。然后Shell会将词元里面的特殊字符进行拓展,拓展完成后才会调用相应的命令

Bash允许用户关闭拓展:

1
2
3
4
5
6
7
$ set -o noglob
# or
$ set -f
#重新打开拓展
$ set +o noglob
# or
$ set +f

拓展有许多种,当文件名中包含通配符的时候需要将文件名放在单引号或双引号里面

~目录拓展

~会自动拓展成当前用户的主目录:

1
2
$ echo ~
/home/ajsoabk

~user,表示拓展成用户user的主目录:

1
2
3
4
5
$ echo ~ajsoabk
/home/ajsoabk
#如果后面的用户名是不存在的用户名,则拓展不起作用
$ echo ~notexist
~notexist

~+会拓展成当前所在的目录,等同于pwd命令

1
2
3
$ cd ~/foo
$ echo ~+
/home/ajsoabk/foo

?单字符拓展

?字符代表文件路径里面的任意单个字符,不包括空字符。

1
2
3
# 当前目录存在文件a.txt和b.txt
$ ls ?.txt
a.txt b.txt

如果文件不存在,则不进行拓展

*通配拓展

*字符代表文件路径里面的任意数量的任意字符。但不会匹配隐藏文件(以.开头的文件),如果需要匹配隐藏文件要使用.*

1
2
3
4
5
# 存在文件 a.txt、b.txt和 ab.txt
$ ls a*.txt
a.txt ab.txt
$ ls *b*
b.txt ab.txt

如果没有匹配的文件,则不进行拓展

[]匹配拓展

[]包裹的任意一个字符匹配则匹配成功:

1
2
3
# 存在文件 a.txt 和 b.txt
$ ls [ab].txt
a.txt b.txt

可以在左方括号后紧跟一个^!,表示匹配不在方括号里面的字符

1
2
3
# 存在 aaa、bbb、aba三个文件
$ ls ?[!a]?
aba bbb

如果需要匹配[字符,可以放在方括号内,如果需要匹配-,只能放在方括号内部的开头或结尾,比如[-aeiou],除此之外,-可以用来匹配一个连续的范围,如[a-d]等同于[abcd]

{}全部拓展

{}拓展表示分别拓展成大括号里面的所有值:

1
2
$ echo d{a,e,i,u,o}g
dag deg dig dug dog

大括号内部的逗号前后不能有空格,否则扩展失效

逗号前面可以没有值,表示拓展失效:

1
2
3
$ cp a.log{,.bak}
#等同于
# cp a.log a.log.bak

大括号可以嵌套,也可以与其他模式联用,并且总是先于其他模式进行拓展

{start..end}表示拓展成一个连续序列,并且支持逆序

这种简写形式还可以使用第二个双点号用来指定拓展的步长

1
2
$ echo {0..8..2}
0 2 3 4 6 8

$变量拓展

$开头的词元将被视为变量,变量名除了放在$后面,也可以放在${}里面

1
$ echo $SHELL

${|string*}${!string@}返回所有匹配string的变量名

1
2
$echo ${!S*}
SECONDS SHELL SHELLOPTS SHLVL SSH_AGENT_PID SSH_AUTH_SOCK

$()命令拓展

$()或反引号可以拓展成另一个命令的运行结果,可嵌套,但是结果中的连续空白字符将被替换成单个空格:

1
2
$ echo $(date)
Tue Jan 28 00:01:13 CST 2020

$(())算术拓展

$(())可以拓展成整数运算的结果:

1
2
$ echo $((2+2))
4

[[:class:]]类匹配拓展

  • [[:graph:]]:匹配A-Z、a-z、0-9和标点符号
  • [[:alnum:]]:匹配A-Z、a-z、0-9
  • [[:alpha:]]:匹配A-Z、a-z
  • [[:upper:]]:匹配A-Z
  • [[:lower:]]:匹配a-z
  • [[:digit:]]:匹配0-9
  • [[:punct:]]:匹配标点符号(除了A-Z、a-z、0-9的可打印字符)
  • [[:blank:]]:匹配空格和Tab
  • [[:space:]]:匹配空格、Tab、LF(10)、VT(11)、FF(12)、CR(13)
  • [[:cntrl:]]:匹配ASCII码0-31的不可打印字符
  • [[:xdigit:]]:匹配A-F、a-f、0-9

在第一个方括号后面加上!表示否定

量词语法

量词语法用于控制模式匹配的次数

量词语法有以下五个

  • ?(pattern-list):匹配零个或一个模式
  • @(pattern-list):匹配一个模式
  • *(pattern-list):匹配零个或多个模式
  • +(pattern-list):匹配一个或多个模式
  • !(pattern-list):匹配给定模式外的任何内容
1
2
3
#当前目录下有abctxt和abc.txt
$ ls abc?(.)txt
abctxt abc.txt

shopt命令

shopt命令可以调整Bash的行为,它有好几个参数跟通配符拓展有关

-s参数打开后面跟着的参数,-u关闭后面跟着的参数

  • dotglob,打开后拓展结果可以包含隐藏文件,默认关闭

  • nullglob,打开后让通配符不匹配任何文件名时返回空字符,默认关闭

  • failglob,打开后让通配符不匹配任何文件名时直接报错而不交由命令处理,默认关闭

  • extglob ,打开后支持量词语法,默认打开

  • nocaseglob,打开后让通配符拓展不区分大小写,默认关闭

  • globstar,打开后可以用**匹配零个或多个子目录,默认关闭

    1
    2
    3
    $ shopt -s globstar
    $ ls **/*.txt
    a.txt sub1/b.txt sub1/sub2/c.txt

转义

某些字符在bash里面有特殊含义($,&,*),要想输出这些字符需要在它们前面加上反斜杠,时其变成普通字符,这就叫做转义

1
2
$ echo \$date
$date

反斜杠本身也是特殊字符

是否转义主要有两种区别,一个是包裹字符串的是单引号还是双引号,一个是否使用了-e参数

-e参数会强制转义,不管包裹字符串的是单引号还是双引号。

而在没有-e参数的情况下,单引号包裹的字符串全部原样打印,不会有任何转义或拓展:

1
2
$ echo 'a\\b\nc'
a\\b\nc

只有三个特殊字符在双引号中会保留特殊含义($,` ,\),因此双引号包裹的字符串会对特殊字符进行转义,但不会对不可打印字符进行转义,如:

1
2
3
4
5
6
$ echo "$SHELL"
/bin/bash
$ echo "`date`"
Mon Jan 27 13:33:18 CST 2020
$ echo "a\\b\nc"
a\b\nc

Here文档

Here文档用于输入多行字符串,格式如下:

1
2
3
<< token
text
token

它的格式分为开始标记和结束标记,结束标记必须顶格写

Here文档内部$\保留特殊含义,不支持通配符拓展

1
2
3
4
5
6
7
8
9
10
$ foo='Ajsoabk'
cat << _example_
$foo
"$foo"
'$foo'
_example

Ajsoabk
"Ajsoabk"
'Ajsoabk'

如果不希望发生变量替换,可以把Here文档的开始标记放在单引号之中

1
2
3
4
5
6
7
8
9
10
$ foo='Ajsoabk'
$ cat << '_example'
$foo
"$foo"
'$foo'
_example_

$foo
"$foo"
'$foo'

Here文档的本质是重定向,它将字符串重定向输出给某个命令,相当于包含了echo命令

1
2
3
4
5
$ command << token
string
token
# 等同于
$ echo string |command

所以,Here文档知识和哪些可以接受标准输入作为参数的命令,对于其他命令无效,比如echo命令就不能用Here文档作为参数

此外,Here文档也不能作为变量的值,只能用于命令的参数

Here字符串

Here文档还有一个变体,叫做Here字符串,使用<<<表示,它的作用是将字符串通过标准输入传递给命令

有些命令直接接受给定的参数与通过标准输入接受参数结果是不一样的,如:

1
2
3
$ cat <<< 'hi there'
# 等同于
$ echo 'hi there' | cat

而如果是直接将字符串放在cat命令后面的话则会被解释成字符串

变量

环境变量

环境变量是Bash环境自带的变量,进入Shell时已经定义好了,可以直接使用。

可以通过命令env, printenv来查看所有环境变量

下面是一些常见的环境变量

  • BASH,Shell名称,如:

    1
    BASH=/user/bin/bash
  • BASH_VERSION,Bash持有的shell版本,如:

    1
    BASH_VERSION=4.2.46(2)
  • COLUMNS,屏幕的列数,如:

    1
    COLUMNS=80
  • HOME为用户的主目录,如:

    1
    HOME=/home/ajsoabk
  • LOGNAME为日志的用户名,如:

    1
    LOGNAME=ajsoabk
  • USER当前用户的用户名,如:

    1
    USER=ajsoabk
  • LINUNO返回它在脚本里面的行号

  • FUNCNAME返回一个包含当前函数调用堆栈的数组

  • BASH_SOURCE返回当前脚本调用堆栈

自定义变量

set命令可以显示所有变量(环境变量和自定义变量)已经所有的Bash函数

变量可以重复赋值,后面的赋值会覆盖前面的赋值

如果变量的值本身也是变量,可以使用${!var} 的语法读取最终的值

1
2
3
$ myvar=USER
$ echo ${!myvar}
ajsoabk

export变量

export变量能够被子Shell读取,在子Shell中更改export变量不会影响父Shell,如:

1
2
3
4
5
6
7
8
9
10
$ export foo=bar
# 新建子Shell
$ bash
$ echo $foo
bar
$ foo=baz
# 退出子Shell
$ exit
$ echo $foo
bar

特殊变量

$?为上一个命令的退出码,用来判断上一个命令是否执行成功,若成功则为0,反之则为非零值:

1
2
3
4
$ ls doesnotexist
ls: doesnotexist: No such file or directory
$ echo $?
1

$$为当前Shell的进程ID,可以用来命令临时文件

1
LOGFILE=/t,p/output_log.$$

$_为上一个命令的最后一个参数

1
2
3
4
$ grep dictionary /usr/share/dict/words
dictionary
$ echo $_
/usr/share/dict/words

$0为当前Shell的名称或者脚本名

变量的默认值

1
2
3
4
5
6
7
8
9
10
${varname:-word}
#如果varname存在且不为空,则返回它的值,否则返回word
${varname:=word}
#如果varname存在且不为空,则返回它的值,否则将它设为word并且返回word
${varname:+word}
#如果varname存在且不为空,则返回word,否则返回空值
${varname:?word}
#如果varname存在且不为空,则返回它的值,否则打印出varname: message,并中断脚本的执行
filename=${a:?"filename missint."}
#在脚本中可以用数字1到9表示传入脚本的参数

declare命令

declare命令可以声明一些特殊类型的变量,比如只读类型和整数类型的变量,其语法形式为:

1
declare OPTION VARIABLE=value

其参数有:

  • -a,数组变量
  • -i,整数变量
  • -r,只读变量
  • -x,环境变量
  • -f,输出所有函数定义
  • -F,输出所有函数名
  • -l,变量值总是会被转为小写字母
  • -u,变量值总是会被转为大写字母
  • -p,输出变量信息

不带任何参数的declare命令等同于不带任何参数的set命令

declare命令如果用在函数中,声明的变量旨在函数内部有效,等同于local命令

注意,一个变量声明为整数以后,依然可以被改写为字符串

1
2
3
4
$ declare -i var=12
$ var=foo
$ echo $var
0

上面例子中,变量var声明为整数,覆盖以后,Bash不会报错,但会赋以不确定的值

readonly命令

readonly命令等同于declare -r,用来声明只读变量,有三个参数

  • -f,声明的变量为函数名
  • -p,打印出所有的只读变量
  • -a,声明的变量为数组

let命令

let命令声明变量时,可以直接执行算术表达式

1
2
3
$ let foo=1+2
$ echo $foo
3

let命令的参数表达式如果包含空格,就需要使用引用

命令行参数

命令行参数通过将数据以参数的形式传递给脚本,使脚本更具动态性,如:

1
./bash_script.sh parameter1 parameter2

如何使用命令行参数

  • $0,脚本名称
  • $1-9,存储前9个参数的名称
  • $#,传递给脚本的参数总数
  • $@, 以数组形式存储的参数列表
  • $*,所有参数连接在一起后的形式

Shift命令与参数移位

shift命令能够控制命令行参数整体左移,同时$#也会减少相应个数,默认移一位,如:

1
2
3
4
5
#!/bin/bash
while [ -n "$1" ];do
echo "$@"
shift
done

字符串

可以使用${#varname}获取字符串长度

提取子串

可以使用${varname:offset:length}提取子串,可以省略length

1
2
3
$ count=frogfootman
$ echo ${count:4:4}
foot

offsetlength都可以为负值

1
2
3
4
5
$ foo="This string is long."
$ echo ${foo: -5:2}
lo
$ echo ${foo: -5:-2}
lon

上面例子中,length-2时要排除从字符串末尾开始的2个字符,所以返回lon

搜索和替换

${string#pattern}${string##pattern}可以检查字符串的开头是否匹配并将匹配的部分删除,其中前者是最短匹配,后者是最长匹配

${string/#pattern/sub}${string/##pattern/sub}可以检查字符串的开头是否匹配并将匹配的部分替换,同样的一个最短一个最长

#换成%则是检查末尾,其余同上

${string/pattern/sub}替换第一个最长的匹配

${string//pattern/sub}替换所有最长匹配

1
2
3
4
5
6
#将路径分隔符:换成换行符
$ echo -e ${PATH//:/\\n'}
/usr/local/bin
/usr/bin
/bin
...

改变大小写

${string^^}可以把字符串转为大写

${string,,}可以把字符串转为小写

算术

(())语法可以进行整数的算术运算,并且会自动忽略内部的空格

这个命令在算术结果不为0的时候执行成功,算术结果为0的时候就算执行失败

1
2
3
$ ((3 - 3))
$ echo $?
1

这个命令本身不返回值,如果要读取算数运算的结果,需要在第一个左括号前面加上美元符号

支持的算数运算符包括加减乘除、求余、递增递减、位运算、逻辑运算(包括三目运算符)、赋值运算(包括一系列复杂赋值)、逗号运算以及指数运算(**),注意/的返回结果总是整数

++--的前缀后缀版本的区别与C语言中相同

在算术表达式中可以使用其它进制

  • 0number,八进制
  • 0xnumber,十六进制
  • bass#numberbase 进制的数

expr命令

expr命令支持算术运算,可以不使用(())语法

脚本入门

Shebang行

脚本的第一行通常是指定解释器,即这个脚本必须通过什么解释器执行。这一行以#!Shebang字符开头

如果没有Shebang行,就只能手动将脚本传给解释器来执行

控制流语句

if[-elif-else]-fi

if语法如下:

1
2
3
4
5
6
7
if commands; then
commands
elif commands; then
commands...
else
commands
fi

if后面可以跟任意数量的命令,这时所有命令都会执行,但是判断真伪只看最后一个命令

case结构

case结构用于多值判断,跟包含多个elifif结构等价,但是语义更好

1
2
3
4
5
6
7
8
9
case expression in
pattern )
commands ;;
pattern )
commands ;;
...
* )
commands ;;
esac

如果需要匹配多个条件,可以用;;&终止每个条件块

while循环

格式为:

1
2
3
while condition; do
commands
done

condition可以为命令

until循环

until循环与while循环恰好相反,只要不符合判断条件,就不断循环执行指定的语句,一旦符合判断条件就退出循环:

1
2
3
until condition; do
commands
done

until一般用得比较少,完全可以统一使用while

for...in循环

for...in循环用于遍历列表的每一项

1
2
3
for variable in list; do
commands
done

列表可以是以空格分隔的值(for i in word1 word2 word3; do...

也可以由通配符产生(for i in *.png; do

也可以通过子命令产生(for i in $(cat ~/.bash_profile

in list的部分可以省略,此时list 默认等于脚本的所有参数$@,但是为了可读性最好还是不要省略

for循环

1
2
3
for (( expression1; expression2; expression3 )); do
commands
done

它等同于

1
2
3
4
5
(( expression1 ))
while (( expression2 )); do
commands
(( expression3 ))
done

breakcontinue

与C中相同

select 结构

select结构用于给用户提供选择

1
2
3
4
5
select element
in list
do
commands
done

Bash会对select依次进行下面的处理

  1. select打印一个菜单,内容是列表list的每一项,并且每一项前面还有一个数字编号
  2. Bash提示用户选择一项,输入它的编号
  3. 用户输入以后,Bash会将该项的内容存在变量name,该项的编号存入环境变量REPLY。如果用户没有输入,就按回车键,Bash会重新输出菜单,让用户选择
  4. 执行命令体commands
  5. 执行结束后回到第二步,重复这个过程

下面是一个例子

1
2
3
4
5
#!bin/bash
select brand in Samsung Sony iphone
do
echo "Youve chosen $brand"
done

执行上面的脚本,Bash会输出一个品牌的列表让用户选择

1
2
3
4
1) Samsung
2) Sony
3) iphone
#?

select可以与case结合

test命令

1
2
3
4
5
test expression
# or
[ expression ]
# or
[[ expression ]]

第三种形式还支持正则判断。如果expression表达式为真则test执行成功

文件判断

test命令有许多参数可以用来判断文件状态:

  • [ -a file ],存在
  • [ -b file ],存在且是一个块(设备)文件
  • [ -c file ],存在且是一个字符(设备)文件
  • [ -d file ],存在且是一个目录
  • [ -e file ],存在
  • [ -f file ],存在且是普通文件
  • [ -g file ],存在且设置了组ID
  • [ -G file ],存在且设置了有效的组ID
  • [ -h file ],存在且是符号链接
  • [ -k file ],存在且设置了它的“sticky bit”
  • [ -L file ],存在且是符号链接
  • [ -N file ],存在且自上次读取后已被修改
  • [ -O file ],存在且属于有效的用户ID
  • [ -p file ],存在且是命名管道
  • [ -r file ],存在且当前用户可读
  • [ -s file ],存在且长度大于零
  • [ -S file ],存在且是一个socket
  • [ -t fd ],如果fd是一个文件描述符且重定向到终端则为真。可以判断是否重定向了标准输入输出/错误流
  • [ -u file ],存在且设置了setuid
  • [ -w file ],存在且当前用户可写
  • [ -x file ],存在且当前用户可执行
  • [ file1 -nt file2 ]file1file2的更新时间最近,或者file1存在而file2不存在
  • [ file1 -ot file2 ]file2file1的更新时间最近,或者file2存在而file1不存在
  • [ FILE1 -ef FILE2 ]FILE1FILE2引用相同的设备和inode编号

字符串判断

  • [ string ],不为空

  • [ -n string ],不为空

  • [ -z string ],为空

  • [ string1 = string2],判断等价

  • [ string1 == string2],判断等价

  • [ string1 '>' string2 ],判断string的字典序在string2之后

  • [ string1 '>' string2 ],判断string的字典序在string2之前

    1
    2
    3
    4
    $ str1=abc
    $ str2=abb
    $ if [ "$str1" '<' "$str2" ]; then echo "greater"; fi
    greater

整数判断

  • [ -z num1 ],判断为空
  • [ num1 -eq num2 ],判断等价
  • [ num1 -ne num2 ],判断不等价
  • [ num1 -le num2 ],判断小于等于
  • [ num1 -lt num2 ],判断小于
  • [ num1 -ge num2 ],判断大于等于
  • [ num1 -gt num2 ],判断大于

算术判断

可以包裹(())进行算术运算的判断

正则判断

[[ expression ]]这种判断形式支持正则表达式

[[ string1 =~ regex ]],其中=~是正则比较运算符:

1
2
3
4
5
6
7
8
9
#!/bin/bash
INT=-5
if [[ "$INT" =~ ^-?[0-9]+$ ]]; then
echo "INT is an integer."
exit 0
else
echo "INT is not an integer." >&2
exit 1
fi

逻辑判断

可以用&&||!-a-o来结合多个test判断表达式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!bin/bash
MIN_VAL=1
MAX_VAL=100
INT=50
if [["$INT" =~ ^-[0-9]+$ ]]; then
if [[ $INT -ge $MIN_VAL && $INT -le $MAX_VAL ]]; then
echo "$INT is within $MIN_VAL to $MAX_VAL."
else
echo "$INT is out of range."
fi
else
echo "INT is not an integer." >&2
exit 1
fi

使用!操作符时,最好用圆括号确定转义的范围,并且圆括号必须使用引号或者转义,否则会被Bash解释

脚本参数

调用脚本的时候,脚本文件名后面可以带有参数:

1
$ script.sh word1 word2 word3

脚本文件内部可以使用特殊变量引用这些参数

  • $1-9,脚本的第一个到第九个参数
  • $#,参数的总数
  • $@,以数组形式存储的全部的参数
  • $*,以$IFS值的第一个字符(默认为空格)分隔的全部的参数

如果脚本的参数多于9个,那么第十个参数可以用${10}的形式引用,以此类推

shift命令

shift 命令可以改变脚本参数,每次执行都会移出脚本的前几个参数(默认为1),并将后面所有的参数向前移相应位数,$#的值也会相应减少(如果原来有参数的话)

getopts命令

getopts命令用在脚本内部,可以解析复杂的脚本命令行参数,通常与while循环一起使用,去除脚本所有的带有前置-的参数,其形式为:

1
getopts opt name

第一个参数opt是字符串,给出脚本所有的连词线参数(不带连词线)。

比如某个脚本可以有灿哥配置项参数-lh-a,其中只有-a可以带有参数值,而-l-h是开关参数,那么getopts的第一个参数写成lha:,顺序不重要。注意,a后面有一个冒号表示该参数带有参数值

第二个参数name是一个变量名,用来保存当前取到的配置项参数,即lh、或a

以下是一个使用getopts获取参数的例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
while getopts 'lha:' OPTION; do
case "$OPTION" in
l)
echo "linuxconfig"
;;
h)
echo "h stands for h"
;;
a)
avalue="$OPTARG"
echo "The value provided is $OPTARG"
;;
?)
echo "script usage: $(basename $0) [-l] [-h] [-a somevalue]" >&2
exit 1
;;
esac
done
shift "$(($OPTIND - 1))"

变量OPTION保存的是当前处理的连词线参数(即lha)。如果用户输入了没有指定的参数,那么OPTION等于?

如果某个连词线参数带有参数值,那么$OPTARG保存的就是参数值

注意,只要遇到不带连词线的参数,getopts就会执行失败,从而退出while循环。另外,多个连词线参数写在一起的形式,比如command -lhgetopts也可以正确处理

变量OPTINDgetopts开始执行前是1,然后每次执行就会加1

配置项参数终止符--

---开头的参数,会被Bash当作配置项解释,但有时它们是实体参数,如果要确保某个参数不会被当作配置项解释,就要在它前面放上参数终止符--

1
$ ls -- $myPath

exit命令

exit 命令用于终止当前脚本的执行,并向Shell返回一个退出值(0表示正常,1表示发生错误,2表示用法不对,126表示不是可执行脚本,127表示命令没有发现

exit命令与return命令的区别是return命令是函数的退出

source命令

source命令用于执行一个脚本,但不像直接执行脚本时会新建一个子Shell,所以通常用于重新加载一个配置文件,而且source命令执行脚本时不需要export变量

source命令的另一个用途,是在脚本内部加载外部库,这样就可以在脚本里面使用这个外部库定义的函数

source命令有一个简写形式,可以使用一个点(.)来表示

alias命令

alias用于为一个命令指定一个更便于记忆的命令别名,其格式为:

1
alias NAME=DEFINITION

其中NAME是命令别名,DEFINITION是别名对应的原始命令,如:

1
alias search=grep

也可以用来为长命令指定一个更短的别名

1
2
3
$ alias today='date +"%A, %B %-d, %Y"'
$ today
星期日, 十一月 14, 2021

直接调用alias命令可以显示所有别名

unalias命令可以解除别名

获取用户输入

read命令格式如下:

1
read [-options] [variable...]

variable是用来保存输入数值的一个或多个变量名。如果没有提供变量名,环境变量REPLY会包含用户输入的一整行数据

如果用户的输入项少于read命令给出的变量数目,那么额外的变量值为空

如果用户的输入项多于read命令给出的变量数目,那么多余的输入项会包含到最后一个变量中

read命令除了读取键盘输入也可以用来读入文件:

1
2
3
4
5
6
7
#!/bin/bash
filename='/etc/hosts'
while read myline
do
echo "$myline"
done < $filename
# 定向符<将文件内容导向read命令

参数

-t参数设置等待的秒数,环境变量TMOUT也可以起到同样作用

-p参数设置提示信息:

1
read -p "Enter one or more values > "

-a参数把用户的输入赋值给一个数组,下标从0开始:

1
2
3
4
$ read -a people
alice duchess dodo
$ echo ${people[2]}
dodo

-n参数指定读取字符的个数:

1
2
3
4
$ read -n 3 letter
abcdefg
$ echo $letter
abc

-e参数允许用户输入的时候使用readline库提供的快捷键,比如自动补全

-d delimiter将终止符设定为delimiter而不是\n

-r,raw模式,表示不把用户输入的反斜杠字符解释为转义字符

-s,使用户的输入不显示在屏幕上,用于信息保密

-u fd:使用文件描述符fd作为输入

IFS(Internal Field Separator)环境变量

read 命令读取的值默认以空格分隔。可以通过自定义环境变量IFS来修改分隔标志。

IFS的默认值是空格、tab\n,通常取第一个

在文件读取中经常把IFS定义成:;

可以把IFS的赋值命令和read命令写在一行,这样的话IFS的改变仅对后面的命令生效,不然就要用到OLD_IFS变量来恢复IFS

使用内置的read命令:

1
2
3
4
5
6
7
8
#!/bin/bash
echo "Enter your name:"
read user_name
echo "Your name is $user_name"
echo
echo "Enter your age, phonenumber and email: "
read age phonenumber email
echo "Your age is :$age. Your phone is: $phonenumber. Your email is $email"

使用-p参数

Bash函数

Bash函数定义的语法是:

1
2
function fn() {
}

其中function可以省略

下面是一个多行函数的例子,显示当前日期时间

1
2
3
4
today() {
echo -n "Today's date is: "
date +"%A, %B %-d, %Y"
}

删除一个函数可以使用unset命令

1
unset -f functionName

查看当前Shell已经定义的所有函数的详细信息可以使用declare命令

1
$ declare -f

参数变量

函数体内可以使用参数变量,与脚本参数变量是一致的

return命令

return命令可以返回一个值给调用者。如果命令行直接执行函数,下一个命令可以用$?获取返回值

local命令

Bash函数体内直接声明的变量(包括函数体内声明的普通变量)都属于全局变量,整个脚本都可以读取

如果希望声明局部变量,需要使用local命令:

1
2
3
4
5
6
7
8
9
#!/bin/bash
# test.sh
fn (){
local foo
foo=1
echo "fn: foo = $foo"
}
fn
echo "global: foo = $foo"

其运行结果为:

1
2
3
$ bash test.sh
fn: foo = 1
global: foo =

数组

数组是一个包含多个值的变量,成员的编号从0开始

数组可以采用一次性赋值的方式创建

1
2
3
4
5
6
7
8
9
10
array=(val1 val2 ... valn)
# 也可以
array[0]=val1
array[1]=val2
...
# 也可以
array=([2]=val3 [0]=val1 [1]=val2)
#也可以只为某些值指定位置
names=(hater [5]=duchess alice)
#上面例子中alice是6号位

成员读取

数组的成员读取方式为${arr[n]}。如果没有花括号,Bash会读取arr的第一个元素,再把[n]原样输出

可以用${arr[@]}${arr[*]}获取数组的所有成员

将其放在双引号中时,后者会将数组元素合并成一个字符串返回

所以拷贝一个数组的最方便方法就是:

1
$ hobbies=( "${activities[@]}" )

提取数组序号

${!arr[@]}${!arr[*]}可以返回数组的成员序号

因此可以使用这种语法循环数组的下标

1
2
3
4
arr=(a b c d)
for i in ${!arr[@]};do
echo ${arr[i]}
done

提取数组成员

${arr[@]:pos:len}的语法可以提取一个区间内的成员

1
2
3
$ food=( apples bananas cucunmbers dates eggs fajitas grapes )
$ echo ${food[@]:1:3}
bananas cucumbers dates

如果省略length则返回从指定位置开始的所有成员

追加数组成员

可以使用+=赋值运算符追加数组成员

删除数组

使用unset命令删除数组或数组成员

关联数组

declare -A可以声明关联数组

1
2
3
delcare -A colors 
colors["red"]="#ff0000"
colors["green"]="#00ff00"

访问关联数组成员的方法几乎与整数索引数组相同

set命令与shopt命令

set命令可以帮助你写出更安全的Bash脚本

直接运行set会显示所有的环境变量和Shell函数

-u

设置了-u参数之后,脚本遇到不存在的变量就会报错并停止执行

-u参数和-o nounset是等价的

-x

设置了-x参数之后,脚本每运行一条命令就会在终端输出,用于调试,与-o xtrace等价

如果要关闭命令输出,可以使用set +x

-e

设置了-e参数之后,脚本只要发生错误(返回值非0),就会终止执行

有些命令的非零返回值可能不表示失败,这时可以使用command || true使得该命令即使执行失败也不会终止执行

等价于-o errexit

-o pipefail

set -e不适用于管道命令

管道命令指多个子命令通过管道运算符|组合成一个大的命令。Bash会把最后一个子命令的返回值作为整个命令的返回值。

set -o pipefail用来保证只要一个子命令失败整个管道命令就失败

-E

设置了-e参数会导致函数内的错误不会被trap命令捕获,加上-E参数后可以使得函数也能继承trap命令

1
2
3
4
5
6
7
8
9
#!/bin/bash
set -Eeuo pipefail
trap "echo ERR trap fired!" ERR
myfunc()
{
# 'foo'是一个不存在的命令
foo
}
myfunc

执行上面这个脚本就可以看到trap命令生效了

1
2
3
$ bash test.sh
test.sh:行9: foo:未找到命令
ERR trap fired!

-n

等同于-o noexec不运行命令,只检查语法是否正确

-f

等同于-o noglob表示不对通配符进行文件名拓展

-v

等同于-o verbose,表示打印Shell接收到的每一行输入

总结

上面介绍的set命令的几个参数,一般都放在一起使用:

1
set -Eeuxo pipefail

这种写法建议放在所有Bash脚本的头部

另一种方法是在执行Bash脚本的时候,从命令行传入这些参数

shopt命令

shopt命令用来调整Shell 的参数,跟set命令的作用类似

直接输入shopt可以查看所有参数以及其状态,也可以单独查询某个参数的状态

-s用来打开某个参数

-u用来关闭某个参数

-q也用来查询某个参数是否打开,但不直接输出查询结果,而是通过shopt命令的返回结果$?表示查询结果:

1
2
3
$ shopt -1 globstar
$ echo $?
1

mktemptrap

Bash脚本有时需要创建临时文件或临时目录,常见的做法是在/tmp目录里面创建文件或目录,但这样做有很多问题,使用mktemp命令是最安全的做法

临时文件的安全问题

/tmp目录是所有人可读写的,如果攻击者知道临时文件的文件名就可能导致严重的安全问题。

而且脚本意外退出时往往会糊涂清理临时文件

生成临时文件淫应当遵循下面的规则

  • 创建前检查文件是否已经存在
  • 确保临时文件已成功创建
  • 临时文件必须有权限限制
  • 临时文件名要不可预测
  • 脚本退出时要删除临时文件

mktemp

直接运行mktemp命令就能生成一个临时文件,其文件名随机并且只有用户本人可读写

为了保证脚本退出时临时文件被删除,可以使用trap命令指定退出时的清除操作

1
2
3
4
#!/bin/bash
trap 'rm -f "$TMPFILE"' EXIT
TMPFILE=$(mktemp) || exit 1
echo "Our temp file is $TMPFILE"

-d参数可以创建一个临时目录

-p参数可以指定临时文件所在的目录,默认使用$TMPDIR环境变量指定的目录,如果这个变量没设置则使用/tmp目录

-t参数可以指定临时文件的文件名模板,模板末尾至少包含索格连续的X字符表示随机字符,默认的文件名模板是tmp.后接十个随机字符

trap命令

trap命令用来在Bash脚本响应系统信号,其形式为:

1
$ trap [action] [signal1] [signal2] ...

其中action是一个Bash命令,常用的信号有

  • EXIT,编号0,退出脚本时产生
  • HUP,编号1,脚本与所在的终端脱离联系
  • INT,编号2,用户按下ctrl + C,意图让脚本停止运行
  • QUIT,编号3,用户按下ctrl+/,意图退出脚本

注意,trap命令必须放在脚本的开头,否则它上方的任何命令导致脚本退出,都不会被它捕获

文件权限

可以通过ls -l命令来罗列出所有文件和目录

img

上图七列分别是:

  • 文件类型(-常规文件,c特殊档案,p命名管道,b块设备,s套接字,d目录,l链接)及超级用户、用户组与其他用户的权限(r阅读权限,w写入权限,x执行权限,-占位)
  • 存储块的数量
  • 文件的所有者或具有管理权限的超级用户
  • 所有者、筹集用户组
  • 文件大小
  • 文件的最后修改日期
  • 文件或目录的名称

chmod命令可以更改不同用户类型的文件权限,其基本形式为

1
2
3
chmod [class][operator][permission] filename
#具体为
chmod [ugoa][+or-][rwx] filename

u超级用户g用户组o其他用户a所有类型

+添加-删除权限

r读取w修改x运行

重定向

输出重定向

>会以命令中的写入内容覆盖原文件内容,如果指定的文件不存在,那么它将会创建一个以指定文件名命名的新文件

1
2
3
4
5
#!/bin/bash
writefile=WriteFile.txt
$ echo "Ajsoabk:www.ajsoabk.xyz" > $writefile
#使用cat命令打印文件内容
$ cat $writefile

>>则是内容附加,如果文件不存在也会新建

输入重定向

<,与<<

深入理解

  • stdin:标准输入文件,其文件描述符为0,默认由此读取数据
  • stdout:标准输出文件,其文件描述符为1,默认向它输出数据
  • stderr:标准错误文件,其文件描述符为2,默认向它写入错误信息
1
2
#将stdin重定向到file1,将stdout重定向到file2
$ command < file1 > file2

文件相关

过于简单:cdmkdir,statrmdir, rm(删除目录或文件)

touch命令可以用来修改文件读取时间和修改时间,-t参数自定义修改时间

cat 命令

cat的全拼是concatenate,主要有三大功能

显示整个文件

1
$cat filename

从键盘创建新文件

1
2
#将stdout重定向到filename
$cat > filename

文件合并

1
$cat file1 file2 > file

参数:

  • -nor-number输出带行数
  • -bor-number-nonblank,输出带行数,但对空行不编号
  • -sor-squeeze-blank,当遇到有两行以上的空行,压缩为一行空行
  • -vor-show-nonprinting

比特币:一种点对点的电子现金系统

比特币的经典文章必须好好研读一下

交易

转出者将该币的前一个交易地址与转入者的公钥打包后签名

首要的问题当然是转入者没法验证转出者是否双花,传统的解决方法是让可信任的权威机构或银行来检查每笔交易以防止双花,每笔交易的币都需要由转出者给到银行、再由银行给到转入者。这一方法的问题是整个系统都高度依赖于中央银行。

我们需要让转入者能独立验证交易的合法性,这要求转入者知道所有的交易信息,因此每笔交易都需要在网络上公开。我们还需要让所有参与这笔交易的人对这笔钱的历史交易信息有共识。转出者需要让每笔交易都能被大部分节点承认。

timestamp server

timestamp server记录一系列的包含时间戳的区块并将其哈希值广泛公开。每个时间戳都包含了前一个区块的哈希值。在这样的一条链上,每加入一个新区块都会巩固前面的区块

Proof-of-Work

为了在点对点的基础上实现这样的分布式timestamp server,我们需要使用工作量证明(Pow)机制。工作量证明机制需要通过枚举找到一个值,这个值在被某些哈希算法转换后(如SHA-256)得到的哈希值以数个连续的零开头。找这个值所需要的时间与零值的个数要求呈指数关系。但一旦找到,其他节点验证这个值的合法性则很快。(跑一遍SHA-256即可)

在这样的一个时间戳网络内,我们不断枚举nonce值直到这个区块的哈希值以一连串符合要求的0值开头。有了这样的算力投入,要想篡改区块就必须付出同等的代价。由于后面的区块包含了前面区块的哈希,因此篡改单个区块后还需要篡改其后面的所有区块。

Pow机制帮助大家形成对代表的共识。如果每个IP地址都有一个投票权(one-IP-address-one-vote),那么投票肯定会被购买了大量IP地址的人所操控。Pow本质上是(one-CPU-one-vote)。系统中的最长链就是大家的共识,大家在这条链上投入了最多的算力。只要主要的算力由诚实节点所控制,那么合法的链条就一定会增长得最快。为了修改一个过去的区块,攻击者必须投入该区块以及其后所有区块上曾被投入的算力,并且必须赶超诚实节点所维护的最长合法链。我们将稍后展示一个稍慢一步的攻击者(指没来得及挖出最新区块)追上最长合法链的可能性将随着后续区块的增加指数下降

为了适应增长迅速的硬件处理速度和随时间变化的挖矿收益,挖矿难度是随过去一段时间内每小时挖出区块的平均值决定的。如果区块产生的速度过快,挖矿难度将自动升高

Network

这个网络的运行有以下步骤:

  1. 给所有节点广播新的交易信息
  2. 每个节点将自己收到的交易信息放进区块中
  3. 每个节点投入算力来找到符合工作量证明难度的哈希值(挖矿)
  4. 当一个节点挖到了矿,它将其广播给其他所有节点
  5. 只有一个区块内的所有交易都是合法且有效的时候,节点才会认为这个区块合法并承认它
  6. 一个节点承认一个区块的表现是它在这个区块后挖矿

节点总是承认最长合法链并一直投入算力来延长它。如果两个节点同时广播了两个不同的区块,其他节点分别会率先接收到其中一个。这样的话,这些节点就会在自己第一个接收到的区块后挖矿,这样的平衡不会维持很久,因为总会有新的区块被率先挖出来,这样的话其中一个分支就会变得更长,工作在更短分支上的节点也会立刻转入新的最长合法链

新的交易信息不需要直接发送到所有节点。只要它被发送到了足够多的节点,这些信息很快就会被写入区块。这样的广播也能适应丢失消息的情况。如果一个节点没有接收到某个区块,在接收到下一个区块的时候它会发现自己少接收了一个

Incentive

按照惯例,区块内的第一笔交易是一笔铸币交易,给新区块的创造者发行了新的币。这样的设计能给节点更大动力来维持比特币网络的运行,并且提供了一种发行货币并流通的方式,这样不需要任何中央机构就能发行新的比特币了

交易费同样也是动力之一。如果一笔交易的输出小于输入,其差额就是支付给区块挖出者的交易费。只要一个预先确定的定量金额的比特币进入了市场,挖矿的动力就完全转换成了交易费,系统也就不会再有通胀了

Reclaiming Disk Space

只要一个币的最近一次交易被写入了足够多的区块,为了节约磁盘空间,在其之前的交易信息就可以被抛弃。为了尽量节约空间而不打破区块的哈希,交易将被以哈希形式存储在默克尔树上,只有根哈希被包含进了区块头的哈希。过去的区块能通过将除了根哈希外的所有分支都除去从而大大节约磁盘空间,因为这些分支上的哈希都没有存储的必要

一个不包含具体交易信息的区块头大约是80字节。我们假设每十分钟挖出一个区块,80 bytes * 6 * 24 * 365 = 4.2MB/year。2008年的计算机基本都有2GB的内存,并且摩尔定律预测现在的增长速度可能是1.2GB/year,因而就算区块头必须被放在内存中,也并没有存储问题

Simplified Payment Verification

不运行一个全节点也是可以验证交易合法性的。一个用户只需要通过询问网络中的其他节点来获得最长合法链的所有区块头,并且获得这个交易所在的默克尔树的区块及其路径。用户不能自己检查交易是否正确,但只要这个区块后接了足够多的区块,他就能确定整个网络承认了这个交易

实际上,只要诚实节点控制着网络,这样的验证就是可信赖的,但如果恶意节点掌控了整个网络,它就会变得很脆弱。网络上的节点可以自己验证交易合法性,但只要攻击者一直掌控着网络,上面这种简化的验证过程则很容易被攻击者所伪造的交易信息所欺骗。对抗攻击者的其中一个策略是从网络上其他节点中接收警报,这驱使用户的软件下载下全节点的信息以及危险的交易来确认警报。一些经常处理交易的公司可能会想运行自己的全节点来保证独立性和安全性,还能保证更快的验证

Combining and Splitting Value

尽管控制单个币的流动是可行的,但在交易中写明每个币的流向将会很累赘。为了让价值能够被拆分与合并,每笔交易都能包含多个输入与输出。一般情况下既可以让一笔大交易的输出成为当前交易的唯一输入,也可以让多笔小交易的输出成为当前交易的多个输入。最多只能有两个输出,一个用于支付,另一个用于返还,如果需要的话,返还给转出者

需要注意的是依赖于之前多笔交易的扇入过程并不麻烦,因为不需要将前向交易的完整信息复制到当前交易中来

Privacy

传统的银行模式通过限制人们获取其他人的信息来实现某种程度的隐私保护。由于比特币网络天然需要公开所有交易,因而这样的方法无法复用,但是隐私仍然可以通过打破信息在某个地方的流通来实现保护:保持公钥的匿名性。公众能看到某个节点给另一个节点转了帐,但不能将这笔交易联系到任何具体的人身上。这有点像股票交易的信息流通方式-每笔买入或卖出的时间与数额都是公开的,但不能得知是谁进行了这样的交易

除此之外,每笔交易都可以通过引入新的公私钥对来防止某些交易跟一个共同的拥有者相联系。在一些扇入交易中有些联系仍然是不可避免的,因为这会揭示这些输入的交易所在节点被同一个人所拥有。其中的风险在于如果某人与其公钥对应起来了,这样的联系会告诉我们其他的很多交易也是属于同一个拥有者的

Calculation

数学证明略。。。

引言

RSA加密算法是一种非对称加密算法,在公开密钥加密和电子商业中被广泛使用。RSA是由罗纳德·李维斯特(Ron Rivest)、阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)在1977年一起提出的。当时他们三人都在麻省理工学院工作。RSA 就是他们三人姓氏开头字母拼在一起组成的

​ ————————-Wikipedia

RSA是一种非常广泛使用的非对称加密算法,如其名,这种算法首先是一种加密算法。加密算法可不止是加密,而是包括密钥准备、加密、解密等等全过程的一种算法。那么加密解密为何如此重要呢?

在网络上,信息是可以完美复制的,节点与节点在信号发送上没有区别,这就导致了一个问题,我怎么知道某段冷冰冰的01信号是谁发给我的?同样的,由于信号传递过程中难免要经过其他节点,如果我不想让其他节点知道我发送的信息我又要怎么办呢?

这些问题就可以通过理想的公私钥加密体系完美解决。公钥私钥的区别只在于是否公开,而两者都可以用来加密,只是用公钥加密后的信息只能被私钥解密,被私钥加密后的信息也只能被公钥解密。这就对应了上面两个问题的解决方法。

首先,公钥完全公开透明,每个人都可以用公钥加密,但是产生的密文却只有私钥才能解密成明文,这样保证了有用情报只会被拥有私钥的人接收,我们就能把信息发给拥有私钥的那个人而不用担心被别人得知了。

反过来呢?拥有私钥的人对某段信息用私钥加密之后,产生的密文能被所有人解密成明文,这样又有什么效果呢?为了把明文和无效信息区分开来,假设我们约定了明文中至少要包含的有效信息(比如发布时间等等),那么密文就与加密者产生了对应关系,我们只需用加密者发布的公钥做一下解密,再验证一下明文中是否有这些有效信息,就能确认这段信息是不是由私钥拥有者发布的了。这样信息就有了归属,我们就能确认某段信息是我们想要的人发给我们的了。而这种私钥加密的过程也称为签名

“非对称”并非核心

“ 非对称加密 ”本身没什么厉害的,我们可以随便设计一个非对称的加密算法,就让乘私钥作为加密,乘公钥作为解密,那么整个原理就是message * privatekey * publickey = message,在这里,公钥与私钥的对应关系就是privatekey = 1 / publickey。你应该能发现,这样的加密解密似乎没啥保密性可言,任何学过小学数学的人都能很快地从公钥推出私钥,也就能随意冒充你来发布消息了。因此,“似乎”保证私钥与公钥难以互相推导是非常重要的

不能让公钥简单推到私钥是显然的,但为什么说也不能让私钥简单推到公钥呢?这里我们要明确一点,公钥与私钥只是互成一对,并没有形式上的区别,我既能用公钥加密,也能用私钥加密。那如果算法保证了只知道公钥的时候难以推出私钥的话,反过来也是一样的。在只知道私钥的情况下也难以推出公钥,注意!是只知道私钥!而生成这一对公私钥的过程中是产生了很多过程变量的,这些过程变量才是算法生成公私钥对的某种依据

总结来说,RSA等一众非对称加密算法通过某个数学过程产生了互成一对但难以相互推导的公钥与私钥,然后大家就能愉快地用公私钥来在网络上加密通信了。

取模

求余,一个小学就接触到的数学运算,那时候我们把除法得到的整数后加几个点,再接上一个数表示余数:

$$ 5 \div 3 = 1 \dots 2$$

这样的写法中,余数表现得就像它的名字一样——有点多余。当时的我们可没想到,这么简单的一个余数及其相关的运算,竟然能在数论中爆发出那么强大的力量

废话少说,让我们再多多观察观察这个运算,为了不考虑向下取整与向0取整,我们忽略负数的情况

在上面的例子中,如果我们不关注商而只关注余数,那么包括2、5、8等等在内的一系列数对3求余结果都是2,包括1、4、7在内的一系列数对3求余结果都是1,类似的,如果我们只关注整数n对m求余后的结果,那么所有的n就能根据这个结果分成m个集合,我们把这样划分后在同一个集合内的两个数称为模m同余,这样的集合称为同余类,求余运算的新形式也就这么出现了

两个整数a,b,若它们除以正整数m所得的余数相等,则称a,b对于模数m同余,记作:$$a \equiv b\ (\ mod\ m)$$

对于一个运算符,最重要的概念是什么?

overlapping, substantial, redundancy, predicate, mediate, hassle, mint, inflation, lunge, compact, broadband, a.k.a., in volume, micropayment, malleability, scalability, ledger, refactor, analogous, mediate, jeopardize

  1. dues, the official payments that you make to an organization you belong to

  2. evasion, the act of avoiding something or someone

    eg: tax evasion

  3. ballot, a piece of paper on which you write your vote

  4. implement, to put a plan into action

  5. slip,a small piece of paper

  6. reminiscent -> reminiscent of sb/sth, making you remember a particular person, event, or thing.

    eg: That song is so reminiscent of my adolescence

  7. preclude, to prevent something or make it impossible, or prevent someone from doing something.

  8. deficit, the total amount by which money spent is more than money received.

  9. issue, to produce or provide something official.

  10. encompass, to include different types of things.

  11. custodial, referring to or having the responsibility of protecting, caring for, or maintaining something or someone.

  12. ecology, the relationships between the air, land, water, animals, plants, etc., usually of a particular area.

  13. proliferate, to increase a lot and suddenly in number.

  14. actuate, to make a machine work or be the reason a person acts in a certain way.

  15. altruism, willingness to do things that bring advantages to others, even if it results in disadvantage for yourself.

  16. seamlessly, without any sudden changes, interruptions, or problems.

  17. -centric, having a particular type of person, place, or thing as your most important interest; seen from the point of view of a particular type of person, place, or thing.

  18. paradigm, a model of something, or a very clear and typical example of something.

  19. commodity, a substance or product that can be traded, bought, or sold.

  20. utility, able to do several different things well.

  21. pervasive, present or noticeable in every part of a thing or place.

  22. intervention, the action of becoming intentionally involved in a difficult situation, in order to improve it or prevent it from getting worse.

  23. verge, the edge or border of something.
    eg: They set up camp on the verge of the desert

  24. daemon, background processes that worked tirelessly to perform system chores.

  25. ventilator, a machine that helps people breathe when they have difficulty breathing on their own, by forcing air in and out of their lungs.

  26. avionics, the electronic devices of an aircraft or spacecraft.

  27. telemetry, the science or process of collecting information about objects that are for away and sending the information somewhere electronically.

  28. rocketry, the design and construction of rockets.

  29. intermittent, not happening regularly or continuously; stopping and starting repeatedly or with periods in between.

  30. erratic, moving or behaving in a way that is not regular, certain, or expected.

  31. afflict, if a problem or illness afflicts a person or thing, they suffer from it.

  32. mitigate, to make something less armful, unpleasant, or bad.

  33. destabilizing, making a government, area, or political group lose power or control, or making a political or economic situation less strong or safe, by causing changes and problems.

  34. malicious, intended to harm or upset other people.

  35. exploitable, able to be used unfairly, for someone’s own advantage.

  36. snippet, a small and often interesting piece of news, information, or conversation.

  37. undue, to a level that is more than is necessary, acceptable, or reasonable.
    eg: Such a high increase will impose an undue burden on the local tax payer.

  38. glean, to collect information in small amounts and often with difficulty
    eg: They’re leaving on Tuesday - I managed to glean that much (from them)

  39. esoteric, very unusual and understood or liked by only a small number of people, especially those with special knowledge.

  40. de facto, /dei…/, existing in fact, although perhaps not intended, legal, or accepted.

  41. imbue sth./sb. with sth., to fill something or someone with a quality or feeling.
    eg: Her poetry was imbued with a love of the outdoors.

  42. intercept, to stop or catch something or someone that is on the way from one place to another so that it does not reach the intended place.

  43. flaky, behaving in a way that is strange, not responsible or not expected.

  44. malice, /`m…/, the wish to harm or upset other people
    eg: I bear him no malice.

  45. proprietary, owned and legally controlled by a particular company.
    eg: This is proprietary software, and you have no right to copy it without a license from the owner.

  46. overdue, not done or happening when expected or when needed; late;

  47. sentinel, a person employed to guard something

  48. the gory details, the interesting and usually personal pieces of information about a person or event.

    • Come on, I want to know all the gory details about your date with Jon.
  49. terse, using few words, sometimes in a way that seems rude or unfriendly.

    • “Are you feeling any better?” “No!” was the terse reply.
  50. declarative sentence, a sentence that makes a statement or states a fact.

  51. per se, by or of itself

    • Research shows that it is not divorce per se that harms children, but the continuing conflict between parents.
  52. dictate, to give orders, or tell someone exactly what they must do, with total authority.

  53. verbose, using or containing more words than are necessary.

  54. the whole shebang, the whole of something, including everything that is connected with it.

  55. hail, to publicly praise or who approval for a person or an achievement.

  56. prompt, if a computer prompts you to do something while performing a task, it gives you a message the tells you what action to take next.
    eg: After you’ve downloaded the program, you will be prompted to restart your PC.

  57. at the expense of sth., If you do one thing at the expense of another, doing the first thing harms the second thing.

  58. deprecate, to not approve of something or say that you do not approve of something;
    to say that you think something is of little value or importance.

  59. archetype, a typical example of something, or the original model of something from which others are copied.

  60. foretaste, something that gives you an idea of what something else is like by allowing you to experience a small example of it before it happens
    eg: The recent factory closures and job losses are just a foretaste of the recession that is to come

  61. corrode, If metal corrodes, or if something corrodes it, it is slowly damaged by something such as rain or water
    eg: Steel tends to corrode faster in a salty atmosphere.

  62. dud, something that has no value or that does not work.
    eg: Are there any more batteries? This one’s a dud.

  63. illiterate, unable to read and write.

  64. subservient, (dis) willing to do what other people want, or considering your wishes as less important than those of other people.

    • His other interest were subservient to his compelling passion for art
  65. shun, to avoid something

    • She has sunned publicity since she retired from acting.
  66. assassinate, to kill someone famous or important.

  67. eradicate, to get rid of something completely or destroy something bad.
    eg: The disease that once claimed millions of lives have now been eradicated

  68. mutilation, the act of damaging something severely, especially by violently removing a part

  69. polygamy, the fact or custom of being married to more than one person at the same time.

  70. anthem, a song that has special importance for a particular group of people, and organization, or a country, often sung on a special occasion.

  71. spatial, relating to the position, area, and size of things.

  72. annexe or annex, an extra building added to a larger building.

  73. herald, to be a sign that something important, and often good, is starting to happen, or to make something publicly known, especially by celebrating or praising it.

    • Everything from tyres to toothbrushes might soon be in communications range, heralding the dawn of a new era.
  74. gadget, a small device or machine with a particular purpose

  75. rivalry, a situation in which people, businesses, etc. compete with each other for the same thing.

    • There’s fierce rivalry to get the job.
  76. another/the final nail in the coffin, an event that causes the failure of something that had already started to fail.

    • Is COVID-19 the final nail in the coffin for US hegemony?
  77. reverberations, effects that spread and affect a lot of people

    • Reverberations from the 2007 financial crisis.
  78. savor, to enjoy food or an experience slowly, in order to enjoy it as much as possible.

    • You make me want to savor every moment.
  79. diffusion, the action of spreading in many directions.

    • Power diffusion has been greater in the economic sphere, where emerging powers- particularly China, India and Brazil- are more competitive.
  80. gauge, to calculate an amount, especially by using a measuring device.

    • Use a thermometer to gauge the temperature.
  81. in a league of its own, completely superior to others to others of one’s or its kind

    • As a lawyer, Janice is truly in a league of her own.
  82. implode, to fall towards the inside with force.

    • The vacuum inside the tube caused it to implode when the external air pressure was increased
  83. prowess, image-20211226210440595,great ability or skill.

    • He’s always boasting about his sexual prowess
  84. eminence, the state of being famous, respected, or important.

  85. make inroads/an inroad, to start to have a direct and noticeable effect (on something).

    • In terms of more relevant forms of economic prowess- financial power, currency power and its derivative monetary power- the United States continues to excel even as competitors make significant inroads.
  86. underpin, to give support, strength, or a basic structure to something.

    • He presented data to underpin his argument.
  87. alienate, to cause someone or a group of people to stop supporting and agreeing with you.

  88. asinine, extremely stupid

    • Association for the Alleviation of Asinine Abbreviations and Absurd Acronyms
  89. exploit, to use something in a way that helps you

    • We need to make sure that we exploit our resources as fully as possible.
  90. silhouette, a dark shape seen against a light surface.

    • An unidentified witness was shown on camera in silhouette
  91. hype, information that makes something seem very important or exciting.

    • The Internet of Things is neither science fiction nor industry hype, but is based on solid technological advances and visions of network ubiquity that are zealously being realized.
  92. unobtrusive, not noticeable; seeming to fit in well with the things around.

    • Make-up this season is unobtrusive and natural-looking
  93. devolve, to (cause power or responsibility to) be given to other people.

    • Embedded intelligence in the things themselves can further enhance the power of the network by devolving information processing capabilities to the edges of the network.
  94. toll, a small amount of money that you have to pay to use a road, cross a bridge, etc.

    • Early applications of RFID include automatic highway toll collection…
  95. counterfeit, image-20220108102857871,something that is made to look like the original of something else, usually for dishonest or illegal purposes.

    • This watch may be a counterfeit, but it looks just like the original
  96. draw on sth, to use information or your knowledge of something to help you do something else

    • The Internet of Thing will draw on the functionality offered by all of these technologies to realize the vision of a fully interactive and responsive network environment
  97. champion, a person who enthusiastically supports, defends, or fights for a person, belief, right, or principle.

  98. inception, the beginning of an organization or official activity

    • Since its inception in 1968, the company has been at the forefront of computer development.
  99. forum ,pl fora

  100. consortium, pl consortia, an organization of several businesses or banks joining together as a group for a shared purpose.

  101. sheer, (of size or weight) very large.

    • The sheer size of the engine makes it difficult to transport
  102. deployment, the use of something or someone, especially in order to achieve a particular effect.

    • Good solutions are based on the efficient and wise deployment of capital, resources and people.
  103. foster, to encourage the development or growth o ideas or feelings.

    • I’m trying to foster an interest in classical music in my children
  104. consent, permission or agreement.

    • They can’t publish your name without your consent.
  105. consecutive, following one after another without an interruption.

    • We’ve had five consecutive days of rain.
  106. lexicography, the activity or job of writing dictionaries.

  107. veteran, having been involved in a particular activity for a long time.

  108. bore, someone who talks too much about boring subjects.

    • I’m inclined to reserve all judgements, a habit that made me the victim of not a few veteran bores.
  109. reserved, tending to keep your feelings or thoughts private rather than showing them

    • Marcus is more reserved than his brother.
  110. be privy to sth., to be told information that is not told to many people

  111. confidence, a secret, or a feeling of trust that a secret will be kept.

    • I’m telling you this in confidence.
  112. preoccupation, the state of being worried about or thinking about something most of the time.

    • Lately, his preoccupation with football had caused his marks at school to slip.
  113. hostile, showing string dislike; unfriendly.

  114. levity, humor or lack of seriousness, especially during a serious occasion.

    • a brief moment of levity amid the solemn proceedings.
  115. unmistakable, not likely to be confused with something else.

    • There was an unmistakable smell of incense in the air.
  116. quiver, to shake slightly, often because of strong emotion.

    • Lennie’s bottom lip quivered and tears started in his eyes.
  117. feign, image-20220104180030622,to pretend to have a feeling or condition

    • Frequently I have feigned sleep, preoccupation or a hostile levity when I realized by some unmistakable sign that an intimate revelation was quivering on the horizon.
  118. plagiarize, image-20220104181409319,to use another person’s ideas or work and pretend that it is your own.

    • The book contains numerous plagiarized passages.
  119. mar, to spoil something, making it less good or less enjoyable.

    • Sadly, the text is marred by careless errors.
  120. suppression, the act of preventing something from being seen or expressed or from operating.

    • the suppression of free speech.
  121. snob, a person who respects and likes only people who are of a high social class, and/or a person who has extremely high standards who is not satisfied by the things that ordinary people like.

    • I’m a bit of a wine snob/a snob where wine is concerned.
  122. parcel out something, to divide something and five it in parts to different people.

  123. conduct, behavior.

    • The club has a strict code of conduct.
  124. excursion, a short journey usually made for pleasure, often by a group of people.

    • Next week we’re going on an excursion.
  125. exempt, to allow someone not to do something, pay something, etc. that others have to do or pay.

    • Only Gatsby, the man who gives his name to this book, was exempt from my reaction.
  126. promise, the likelihood of success or achievement.

    • She shows great promise as a fiction writer.
  127. regarding, about

    • The company is being questioned regarding its employment policy
  128. supplant, to replace

    • Challengers would have to strike at the heart of US power: to supplant US military dominance and security relationships, unseat the dollar as the global currency and build a dominant financial base.
  129. eclipse, to make another person or thing seem much less important, good, or famous.

    • Is COVID-19 the crisis that will eclipse US hegemony?
  130. erode, to rub or be rubbed away gradually.

    • US hegemony, which requires not just dominance but leadership, has already eroded somewhat.
  131. externalize, outsource

    • In order to cut costs, they decided to externalize certain categories of jobs.
  132. outsource, If a company outsources, it pays to have part of its work done by another company.

  133. delegitimize, image-20220106113714441,to make somethin seem not valid or not acceptable.

    • If he does not take part in the election, it would delegitimize the entire electoral process.
  134. mitigation, the act of reducing how harmful, unpleasant, or bad something is.

    • There has been no significant increase in funding for flood mitigation works.
  135. predicament, an unpleasant or confusing situation that is difficult to get out of or solve.

    • With no money and no job, he found himself in a real predicament.
  136. mission-critical, extremely important or necessary for a company, activity, etc. to operate successfully.

    • A small business may store all its mission-critical data on one PC
  137. surveillance, the careful watching of a person or place, especially by the police or army, because of a crime that has happened or is expected.

    • The police have kept the nightclub under surveillance because of suspected illegal drug activity.
  138. mosaic, image-20220106113639486,a pattern or picture made using many small pieces of colored stone or glass, or the activity or method of making these.

  139. tamper-proof also anti-tamper, made so that you are able to see if anything has been changed, opened, removed, or damaged.

  140. archive, image-20220106113556053, a place where historical records are kept.

  141. entail, to make something necessary, or to involve something.

    • Certain critical or institutional applications may entail nodes with sufficient capabilities to support the requisite P2P functionality.
  142. ensemble, image-20220106114433346, a group o people who perform music together, or a collection of things intended to be used together.

    • I admired her ensemble of coat, hat, and shoes.
  143. synergy, the combined power, profits, etc. that can be achieved by two organizations or groups of people working together rather than separately.

    • The merger will help the manufacturing company achieve synergies that will allow it to remain competitive.
  144. overheads, the regular and necessary costs, such as rent and heating, that are involved in operating a business.

    • Many businesses are moving out of New York because the overheads there are so high.
  145. dissemination, the act of spreading news, information, ideas, etc. to a lot of people.

    • Anything that stands in the way of the dissemination of knowledge is a real problem.
  146. **in the midst of **, in the middle of an event, situation, or activity.

    • I’m sorry but I’m too busy - I’m in the midst of writing a report
  147. intrinsic, being an extremely important and basic characteristic of a person or thing.

    • Design is intrinsic to every product.
  148. heterogeneity, image-20220106123801978, the fact of consisting of parts or things that are very different from each other.

    • Archaeological studies of the tombs have shown the heterogeneity of religious practices in the region.
  149. salient, the salient facts about something or qualities of something are the most important things about them.

    • These salient features of BC make it attractive for delivering distributed privacy and security in IoT.
  150. exemplify, to be a typical example of something.

    • To exemplify our idea, we use the scenario of a smart home in the rest of the paper.
  151. instantiate, to represent or be an example of something.

    • He seems to instantiate a new type of masculinity.
  152. masculinity, the characteristics that are traditionally thought to be typical of or suitable for men.

  153. seduce, to make someone feel attracted to you and want to have sex with you.

    • He felt that she was trying to seduce him.
  154. vintage, produced in the past, and typical of the period in which it was made.

    • You’re wearing our vintage misery
  155. proponent, a person who speaks publicly in support of a particular idea or plan of action.

    • He is one of the leading proponents of capital punishment.
  156. disruptive, changing the traditional way that an industry operates, especially in a new and effective way.

    • Disruptive technologies such as big data and cloud computing have been leveraged by IoT to overcome its limitations since its conception.
  157. silo,image-20220108102648943, to separate something or someone from other things or people

    • This heterogeneity leads to vertical silos and reduces the adoption of the IoT.
  158. millennium, a period of 1,000 years, or the time when a period of 1,000 years ends.

  159. in line with, according to or following something such as a rule or principle.

    • We need to know whether the candidate has beliefs in line with our values.
  160. equitable, treating everyone fairly and in the same way.

    • She charged that women are being denied equitable pay.
  161. evacuation, the act of moving people from a dangerous place to somewhere safe.

    • The evacuation of civilians remains out of the question while the fighting continues.
  162. out of the question, not possible or not allowed.

  163. the whole shebang, the whole of something, including everything that is connected with it.

    • The wedding’s next week, but my parents are taking care of the whole shebang.
  164. stand to do sth., to be in a situation in which it is possible or likely that something will happen to you.

    • Far from being passive followers of that Internet of Things, the developing world stands to greatly influence the implementation and widespread adoption of these emerging technologies.
  165. deformation, the action of spoiling the usual and true shape of something, or a change in its usual and true shape.

    • The deformation of the bones was caused by poor diet.
  166. avalanche, image-20220108104625757, a large amount of ice, snow ,and rock falling quickly down the side of a mountain.

  167. a host of, a large number of something.

    • There’s a whole host of reasons why he didn’t get the job.
  168. plethora, image-20220108104911193, a very large amount of something, especially a larger amount than you need, want, or can deal with.

    • The advent of the Internet of Things will create a plethora of innovative applications and services, which will enhance quality of life and reduce inequalities whilst providing new revenue opportunities for a enterprising businesses.
  169. overarching, most important, because of including or affecting all other areas.

    • Indeed, technology and markets cannot exist independently from the overarching principles of a social and ethical system.
  170. apostrophe, image-20220108193806221,symbol '.

  171. glossary, an alphabetical list, with meanings, of the words or phrases in a text that are difficult to understand.

    • a glossary of technical terms.
  172. generic, shared by, typical of, or relating to a whole group of similar things, rather than to any particular thing.

    • The new range of engines all had a generic problem with their fan blades.
  173. not…but rather.., used to emphasize the opposite thing.

    • The problem is not their lack of funding, but rather their lack of planning.
  174. so much as, but rather.

    • I didn’t listen so much as survive the conversation.
  175. lust, a very strong sexual desire.

    • I don’t think it’s love so much as lust
  176. plague, to cause worry, pain, or difficulty to someone or something over a period of time.

    • My shoulder’s been plaguing me all week.
  177. eon, image-20220110231618008,a period of time of one thousand million years.

    • Scientists guessed that this might be a volcanic rock that had remained unaltered for eons.
  178. sack, to remove someone from a job, usually because they have done something wrong or badly, or sometimes as a way of saving the cost of employing them.

    • He got sacked from his last job.
  179. reside in sth./sb., If a power or quality resides in someone or something, the person or thing has that power or quality.

    • The power to sack employees resides in the Board of Directors.
  180. adage, image-20220110232228615,a wise saying or proverb.

    • He remembered the old adage, “Look before you leap.”
  181. morph, to gradually change or change someone or something, from one thing to another.

    • Now a new study has found that the same regions of the brain that control love also control sex –indicating that sexual desire can actually morph into love
  182. continuum, something that changes in character gradually or in very slight stages without any clear dividing points.

    • It’s not “left-wing or right-wing” - political opinion is a long continuum.
  183. corpus, image-20220110233231085, pl corpora, a collection of written and spoken language used in the study of language and in writing dictionaries.

    • All the dictionary examples are taken from a corpus of billion of words.
  184. craving, a strong feeling of wanting something.

    • I have a craving for chocolate.
  185. consummate, to make a marriage or romantic relationship complete by having sex.

    • The marriage was never consummated.
  186. as much as, almost.

    • He as much as admitted that it was his fault.
  187. strike, When a clock strikes, its bells ring to show what the time is.

    • It was a bright cold day in April, and the clocks were striking thirteen.
  188. nuzzle, to touch, rub, or press something or someone gently and/or in a way that shows your love, especially with the head or nose, usually with small repeated movements.

    • My dog came and nuzzled my foot to try and cheer me up.
  189. vile, unpleasant, immoral, and unacceptable.

    • This vile policy of ethnic cleansing must be stopped.
  190. slip, to go somewhere or put something somewhere quickly, often so that you are no noticed.

    • Just slip out of the room while nobody’s looking.
  191. swirl, the act of moving quickly with a twisting, circular movement, or something that moves in this way.

    • The truck went by in a swirl of dust.
  192. in days gone by, in the past.

    • The house was a train station in days gone by.
  193. gritty, containing grit or like grit.

    • Winston Smith, his chin nuzzled into his breast in an effort to escape the vile wind, slipped quickly through the glass doors of Victory Mansions, though not quickly enough to prevent a swirl of gritty dust from entering along with him.
  194. hall, also hallway, a passage inside a house, apartment building, school, hotel, etc. with doors to other rooms or apartments along its sides.

    • You should not be hanging around in the halls during classes.
  195. rag, a torn piece of old cloth.

    • I use these rags for cleaning.
  196. tack, to fasten something with tacks.

    • At one end of the hallway a coloured poster too large for indoor display, had been tacked to the wall.
  197. depict, to represent or show something in a picture, story, movie, etc.; portray.

    • The movie depicts his father as a tyrant.
  198. moustache, image-20220113142502511(US),hair that a man grows above his upper lip.

    • He shaved off his beard but kept his moustache
  199. ruggedly, in a way that is attractive and strong.

    • He was ruggedly handsome.
  200. make for somewhere/something, to go directly toward someone or something.

    • Winston made for the stairs.
  201. economy drive, an attempt to save money by spending as little as possible.

    • 31% of the workforce will be cut as part of an economy drive.
  202. flight, a set of steps or stairs, usually between two floors of a building.

    • The flat was seven flights up.
  203. flat, a set of rooms for living in that are part of a larger building and are usually all on one floor.

  204. lift-shaft, the vertical shaft in a building which contains a lift platform or cab, and through which it is moved from floor to floor.

    • On each landing, opposite the lift- shaft, the poster with the enormous face gazed from the wall.
  205. contrived, artificial and difficult to believe.

    • It was one of those pictures which are so contrived that the eyes follow you about when you move.
  206. caption, a short piece of text under a picture in a book, magazine, or newspaper that describes the picture or explains what the people in it are doing or saying.

    • “BIG BROTHER IS WATCHING YOU”, the caption beneath it ran.
  207. bloke, a man, often one who is considered to be ordinary.

    • If a woman was sat here and a bloke had locked her in a flat and she’d been forced to jump out you would not be laughing.
  208. conservative, not usually liking or trusting change, especially sudden change.

    • a conservative society.
  209. blasphemy, something that you say or do that shows you do not respect God or a religion.

    • All great truths begin as blasphemies. —George Bernard Shaw
  210. confetti, small pieces of coloured paper that you throw at a celebration, especially over two people who have just been married.

 - A young stripper name Shelly Bauman lost her leg in a freak confetti cannon accident.
  1. LMAO, abbreviation for laughing my ass off

  2. as much, exactly

    • I suspected as much when I heard
  3. director, a manager of an organization, company, college, etc.

    • She has become the director of he new information centre.
  4. draw on/upon, If you draw on or draw upon something such as your skill or experience, you make use of it in order to do something.

    • the ability of participants to draw on outside resources including computers and texts.
  5. exposition, a clear and full explanation of an idea or theory.

    • It purports to be an exposition of Catholic social teaching.
  6. purport, to pretend to be or to do something, especially in a way that is not easy to believe.

    • The study purports to show an increase in the incidence of the disease.
  7. shorty, also shawty, an attractive young woman

    • Hey shorty, what’s up.
  8. meritorious, deserving great praise.

    • an award for meritorious service.
  9. finalist, a person or group competing in a final.

  10. cutoff, a fixed point of level at which something stops

    • 31 March is the cutoff date for applications to be accepted.
  11. critique, a report of something such as a political situation or system, or a person’s work or ideas, that examines it and provides a judgement.

    • She produced a detailed, page-by-page critique of the book
  12. bilateral, involving two groups or countries.

    • France and Germany have signed a bilateral agreement to help prevent drug smuggling.
  13. smuggle, to take things or people to or from a place secretly and often illegally.

    • She was caught trying to smuggle 26 kilos of heroin out of/into the country.
  14. semantic, connected with the meanings of words.

  15. dilation, the process of becoming wider or more open.

    • dilation of blood vessels
  16. pruning, the activity of reducing the number or amount of something.

    • A pruning of the product range and the 30 factories they currently own could produce massive savings.
  17. trade-off, a situation in which you balance two opposing situations or qualities.

    • There is a trade-off between doing the job accurately and doing it quickly.
  18. auxiliary, giving help or support, especially to a more important person or thing.

    • auxiliary staff/nurses
  19. mumble, to speak quietly or in an unclear way so that the words are difficult to understand.

    • He often mumbles, and I never know what he’s asking me.
  20. globetrotter, someone who often travels to a lot of different countries

    • Japan last month, New York next month - you’ve become a regular blobe trotter, haven’t you?
  21. go-getter, someone who is very energetic, determined to be successful, and able to deal with new or difficult situations easily.

    • We only recruit go-getters who will be actively involved in the company’s development.
  22. superstitious, based on or believing in superstitions(= beliefs based on old ideas about luck and magic rather than science or reason)

    • Some people are superstitious about spilling salt on the tale
  23. do-gooder, (dis), someone who does things that they think will help other people, although the other people might not find their actions helpful.

  24. paranoid, feeling extremely nervous and worried because you believe that other people do not like you or are trying to harm you.

    • He started feeling paranoid and was convinced his boss was going to fire him.
  25. fruit loop, someone who is silly or strange.

    • He came across as being a complete fruit loop.
  26. fruity, (of a voice) deep and pleasant.

    • Inside the flat a fruity voice was reading out a list of figures which had something to do with the production of pig-iron.
  27. pig iron, a type of iron that is not pure.

  28. oblong, a flat shape with four sides and four angles of 90 degree and opposite sides of equal length.

  29. plaque, a flat piece of metal, stone, wood, or plastic with writing on it that is attached to a wall, door, or other object.

    • There was a brass plaque outside the door listing the various dentists’ names.
  30. smallish, fairly small, but not very small.

    • A common mistake is to try to cram too much into a smallish bathroom
  31. frail, weak or unhealthy, or easily damaged, broken, or harmed.

    • the country’s frail economy.
  32. meagre, very small in amount or number or not enough in amount or number.

    • Her meagre salary is not enough to pay her living expenses.
  33. overalls, US coveralls, a piece of clothing that covers both the upper and lower parts of the body and is worn especially over other clothes to protect them.

  34. sanguine, image-20220116161609416, red in colour.

    • His face naturally sanguine.
  35. coarse, rough and not smooth or soft, or not in very small pieces.

    • coarse hair
  36. pane, a flat piece of glass, used in a window or door.

    • a pane of glass
  37. eddy, a fast, circular movement of water, wind, smoke, etc.

    • Down in he street little eddies of wind were whirling dust and torn paper into spirals.
  38. harsh, too strong, bright, loud, etc.

    • Though the sun was shining and the sky a harsh blue, there seemed to be no colour in anything.
  39. plaster, to cover a surface or an object with something completely or thickly.

    • She had plastered her bedroom walls with photos of pop stars.
  40. mustachio, a large moustache with curly ends.

  41. a commanding position/view, a position or view from which a lot of land can be seen.

    • The house occupies a commanding position at the top of the valley.
  42. fitful, often stopping and starting and not happening in a regular or continuous way.

    • Down at street level another poster, torn at one corner, flapped fitfully in the wind, alternately covering and uncovering the single word INGSOC.
  43. bluebottle, a big fly with a dark blue shiny body.

    • In the far distance a helicopter skimmed down between the roofs, hovered for an instant like a bluebottle, and darted away again with a curving flight.
  44. dart, a small, thin object with a sharp point that is thrown by hand in a game, shot from a gun, or blown from a tube when used as a weapon.

  45. flight, an occasion when something flies or moves through the air.

    • Modern missiles are so accurate because their flight is controlled by computer.
  46. patrol, (especially of soldiers or the police) to go around an area or a building to see if there is any trouble or danger.

    • The whole town is patrolled by police because of the possibility of riots.
  47. babble, to talk or say something in a quick, confused, excited, or silly way.

    • The children babbled excitedly among themselves.
  48. snoop, to look around a place secretly, in order to discover things or find out information about someone or something.

    • Clara’s husband is snooping on her because he thinks she is seeing another man.
  49. guesswork, the process of making a guess when you do not know all the facts.

    • The projected sales figures are pure guesswork on our part.
  50. conceivable, possible to imagine or to believe.

    • It was even conceivable that they watched everybody all the time.
  51. at any rate, something you say to show that you are going to say something more exactly.

    • I don’t think they liked my idea. At any rate, they weren’t very enthusiastic about it.
  52. scrutinize, to examine something very carefully in order to discover information.

    • He scrutinized the men’s faces carefully/closely, trying to work out who was lying.
  53. revealing, showing something that was not preciously known or seen.

    • A joke can be very revealing about/of what someone’s really thinking.
  54. tower, to be very tall or large, usually in a way that makes people feel respect.

    • We turned the corner and there was the cathedral, towering in front of us.
  55. shore sth up, to stop a wall or a building from falling down by supporting it with building materials such as wood or metal.

    • Were there always these vistas of rotting nineteenth-century houses, their sides shored up with baulks of timber, their windows patched with cardboard and their roofs with corrugated iron their crazy garden walls sagging in all directions?
  56. baulk, also balk, a rough thick piece of wood.

  57. timber, wood used for building.

    • a timber merchant
  58. patch, to put a patch on something.

  59. cardboard, material like very thick, stiff paper, usually pale brown in colour, used especially for making boxes.

    • He was living on the streets for three months, and his home was a cardboard box.
  60. corrugated iron, usually galvanized sheet iron or sheet steel shaped into straight parallel ridges and hollows.

    • The rain drumming on the corrugated iron roof kept me awake last night.
  61. state of the art refers to the highest level of general development, as of a device, technique, or scientific field achieved at a particular time.

  62. on the part of sb. or on one’s part, done or experienced by someone.

    • This was a misjudgment on the part of the government.
  63. puffery, the act of praising someone or something too much in a way that is not sincere.

    • It’s usually easy to tell the difference between sales puffery and fact.
  64. connote, If a word, object, or situation connotes something, it makes you think of a feeling or an idea that is more than its basic meaning.

    • To me, chocolate connotes pleasure and indulgence.
  65. superlative, the form of an adjective or adverb that expresses that the thing or person being described has more of the particular quality than anything or anyone else of the same type.

    • The magazine article contained so many superlatives that I found it hard to believe that what it was saying was true.
  66. ascribe something to someone/something, to consider something to be caused, created, or owned by someone or something.

    • To what do you ascribe the enormous success of your latest book?
    • People like to ascribe human feelings to animals (= believe animals have human feelings)
  67. combustion, the chemical process in which substances mix with oxygen in the air to produce heat and light.

    • Fuel combustion produces energy to run machines.
  68. novelty, the quality of being new and unusual.

    • The novelty of these toys soon wore off and the children became bored with them.
  69. prior art is any evidence that your invention is already known.

    • An existing product is the most obvious form of prior art.
  70. filing, an official record of something.

    • a bankruptcy filing
  71. undergrad, (informal), an undergraduate.

  72. audit, to go to a class or educational course for pleasure or interest, without being tested or receiving a grade at the end.

    • As a senior citizen, he is allowed to audit university classes.

Situations

to explain

  1. shed light on, to provide information about something or to make something easier to understand.
    eg: Tracking technologies have shed light on the birds’ social nature
  2. **a resurgence in sth
  3. by common consent, most people agree.
    • Her latest novel, by common consent, is her best yet.

to tackle

  1. make yourself scarce, to go away from a difficult situation in order to avoid trouble.
    eg: Things were going badly at the meeting, so he made himself scarce.

adjectives for stuff

  1. seminal, containing important new ideas and having a great influence on later work.
    eg: She wrote a seminal article on the subject while she was still a student
  2. pervasive, present or noticeable in every part of a thing or place
  3. pivotal, central and important.
    • Sensors play a pivotal role in bridging the gap between the physical and virtual worlds.

adjectives for thing

  1. inexorably, in a way that continues without any possibility of being stopped

    • Before Trump took office, many scholars and policy-makers believed we were either already in a multipolar world or inexorably moving towards one.

Animal

  1. mastodon, a large animal similar to an elephant, but with fur, that existed on the Earth until around 10,000 years ago.

military

  1. grenade, a small bomb thrown by hand or shot from a gun.
  2. disarm, to take weapons away from someone, or to give up weapons or armies.

medicine && illness

  1. Obsessive-compulsive disorder, OCD
  2. polio, a serious infectious disease that can cause permanent paralysis
  3. meningitis, */..’dg../*a serious infectious disease that causes the tissues around the brain and spinal cord to swell
  4. measles, */`mi:z../*an infectious disease that produces small, red spots all over the body.
  5. dispensary, a place where medicines are prepared and given out, often in a hospital.
  6. pharmaceutical, relating to the production of medicines.
  7. venous, image-20220113145151456,of or relating to the veins.
    • the venous system.
  8. ulcer, a break in the skin, or on the surface of an organ inside the body, that does not heal naturally.
    • a mouth ulcer.

politics && law

  1. dictator, a leader who has complete power in a country and has not been elected by the people
  2. oppression, a situation in which people are governed in an unfair and cruel way and prevented from having opportunities and freedom.
    eg: War, famine and oppression have forced people in the region to flee from their homes.
  3. despotic, having unlimited power over other people, and often using it unfairly and cruelly
  4. general, an officer of very high rank, especially in the army.
  5. outlaw,to make something illegal or unacceptable.
  6. imperialism, a system in which a country rules other countries, sometimes having used force to get power over them.
  7. ideology, a set of beliefs or principles, especially one on which a political system, party, or organization is based.
  8. emancipation, the process of giving people social or political freedom and rights.
  9. subvert, to try to destroy or damage something, especially an established political system
  10. abdicate, if a king or queen abdicates, he or she makes a formal statement that he or she no longer wants to be king or queen.

talking

  1. for someone’s taste, in the opinion of someone based on that person’s feelings about what is appealing, attractive, etc.

sexual

  1. genital, connected with the outer sexual organs, especially the penis or vulva.
  2. vulva, the parts of the female sex organs that are outside the body

COMMERCE

  1. escrow, an agreement between two people or organization in which money or property is kept by a third person or organization until a particular condition is met
  2. penetration, a level of sales, or of increase in sales, of a product or service in a particular area.
  3. debit, (a record of ) money taken out of a bank account

meanings I don’t know

  1. exercise, (formal)to use something
    eg: Dictators are individuals that exercise despotic power
  2. milk, to get as much money or information out of someone or something as possible, often in an unfair or dishonest way
    eg: To stay in power you have to brutally milk every one of all their wealth.

literal

  1. synopsis, a short description of the contents of something such as a film or book

technology

  1. miniaturization, the process of making something very small using modern technology.
    • The silicon chips is a classic example of the benefits of miniaturization.

philosophy

  1. someone who does not know, or believes that it is impossible to know if a god exists.

zodiac

  1. astrology, the study of the movements and positions of the sun, moon, planets, and starts in the belief that they affect the character and lives of people
    • In astrology, a person’s personality is supposed to relate to which star sign they were born under.
  2. sidereal, of or calculated by the stars.
  3. equator, an imaginary line drawn around the middle of the earth an equal distance from the North Pole and the South Pole.
    • Indonesia is/lies on the equator.
  4. ecliptic, image-20220116112359093, the great circle representing the apparent annual path of the sun.
    • The plane to which the equator is tilted 24 was the ecliptic, and the sun moved along the plane
  5. Aries is the first astrological sign in the zodiac,

基础语法

代码规则

1
2
3
4
5
6
7
8
9
10
11
12
package main//文件必须声明包名
import
"fmt"

func main(){
var stockcode = 123//结尾不需要分号
var enddate = "2020-12-31"
var url = "Code = %d&endData = %s"
var target_url = fmt.Sprintf(url, stockcode, enddate)//类似C语言的sprintf
fmt.Println(target_url)
//标识符以大写字母开头意味着该对象对包外可见(public),否则则对包外不可见
}

基本类型

uint,uint8,uint16,uint32,uint64,int,int8,int16,int32,int64,float32,float64,complex64(32位实数和虚数),complex128(64位实数和虚数),uintptr(用于存放指针)

变量声明:

1
2
3
4
5
6
7
8
9
10
11
12
13
var x, y int//如果变量没有初始化,则默认为零值
var (
a int
b bool
)
var c, d int = 1, 2//可以并行赋值
var e, f ,_= 123, "hello", "discarded"//可以是不同类型,还可以用空白标识符_来抛弃值
func main(){
g, h := 123, "hello"//用:=初始化语句的用法只能在函数体中出现
}
var binarynum int = 0b1100//二进制数字
var eightnum int = 0o14//八进制
var hexnum int = 0xc//十六进制

浮点型

float32,即单精度,一位符号位,八位指数位,23位尾数位

float64,即双精度,一位符号位,十一位指数位,52位尾数位

精度主要取决于尾数位数,$$ 2^{-23} \approx 1.19*10^{-7}$$,因此float只能精确到后面6位,有效数字为7位

而$$2^{-52}\approx 2.22*10^{-16}$$,因此精确到小数点后15位,有效位数为16位

  • math.MaxFloat32math.MaxFloat64分别大约是3.4e38和1.8e308
  • float32float64能表示的最小值分别是1.4e-45和4.9e-325

byte与rune

byte占用一个字节,与uint8类型本质上没有区别

1
2
3
var a byte = 65
var b byte = '\101'//\是八进制前缀
var c byte = '\x41'//\x是十六进制前缀

rune,占用四个字节,和int32本质上也没有区别,表示一个Unicode字符

1
var name rune = '中'

string

Go语言的string是用utf-8编码的,英文字母占用一个字节,而中文字母占用3个字节

可以使用双引号或反引号包裹字符串,反引号包裹的字符串会忽略转义

可以用fmt的%q来将原生型字符串还原成解释型字符串

1
2
3
var mystr0 string = `\r\n` \\原生型
var mystr2 string = "\\r\\n"\\解释型
fmt.Printf("%v 的解释型字符串是: %q",mystr01)

匿名变量

又称占位符,或者空白标识符,用下划线表示,其有三个优点

  • 不分配内存,不占用内存空间
  • 不需要你为命名无用的变量名而纠结
  • 多次声明不会有任何问题
1
2
3
4
5
6
7
8
func GetData() (int, int) {
return 100, 200
}
func main(){
a, _ := GetData()
_, b := GetData()
fmt.Println(a,b)
}

new函数

用new创建变量和普通变量声明语句创建变量没有什么区别,除了不需要声明一个临时变量的名字外,我们还可以在表达式中使用new(Type)。

换言之,new函数类似是一种语法糖,而不是一个新的基础概念

1
2
3
4
5
6
7
8
func newInt() *int {
return new(int)
}
//is equivilant to
func newInt() *int {
var dummy int
return &dummy
}

数组与切片

1
2
3
var a [5]int//数组声明
arr01 := [...] int{1, 2, 3}
arr := [4]int{2:3}//在下标为2处初始化为3

切片是数组的抽象,其本身是引用类型。其包含容量、长度和指向底层数组的指针

1
2
3
4
5
6
7
8
9
10
//依赖于数组的声明方式
arr := [...]int{1, 2, 3, 4, 5}
slice1 := arr[1:3]
slice2 := arr[1:3:3]//第三个数影响切片容量,arr[a:b:c]的切片容量为c-a
//空切片声明
var strSlice []string
intSlice := []int{}
//使用make函数构造,make([]Type, size, cap),第三个参数可选
numbers := make([]int, 5,10)//声明初始长度为5,容量为10的切片

1
2
3
4
5
6
7
slice := []int{1}
slice = append(slice, 2)//追加一个元素
slice = append(slice, 3, 4)//追加多个元素
slice = append(slice, []int{7, 8}...)//追加一个切片,其中...表示解包
slice = append([]int{0},myarr...)//在第一个位置插入一个切片
slice = append(myarr[:5],append([]int{5,6}, myarr[5:]...)...)//在中间插入一个切片
fmt.Println(slice)

切片的子切片:

1
2
3
4
5
6
7
number2 := []int{1, 2, 3, 4}
slice1 := number2[2:]
fmt.Println(slice1)// ->[3 4]
slice2 := number2[:3]
fmt.Println(slice2)// ->[1 2 3]
slice3 := number2[1:4]
fmt.Println(slice3)// ->[2 3 4]

const与iota

在定义常量组时,如果不提供初始值,则表示将使用上行的表达式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main
func main(){
//iota 只是在同一个 const 常量组内递增,每当有新的 const 关键字时,iota 计数会重新开始
const (
a = iota //0
b //1
c //2
d = "ha" //"ha"
e //"ha"
f = 100 //100
g //100
h = iota //7
i //8
)
}

类型别名

使用type可以定义一个类型字面量

1
type arr3 [3]int

Chan类型

go后加一个函数,就可以创建一个线程,函数可以为已定义的,也可以是匿名的

1
2
3
4
5
6
7
8
9
10
11
12
13
package main
import "fmt"
func main(){
fmt.Println("main start")
go func(){
fmt.Println("goroutine")//由于Go语言的线程是并发机制,所以这行实际来不及执行
}()
fmt.Println("main end")
}
/*
main start
main end
*/

让线程执行的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package main
import "fmt"
import "time"
func main(){
fmt.Println("main start")
go func(){
fmt.Println("goroutine")
}()
time.Sleep(1*time.Second)
fmt.Println("main end")
}
/*
main start
goroutine
main end
*/

Chan可以理解为队列,通过Chan,并发核心单元可以发送或者接收数据进行通讯,它的操作符是<-

1
2
3
4
5
6
7
8
9
10
11
ch1 := make(chan string)//声明不带缓冲的通道,进和出都会阻塞
ch2 := make(chan string, 10)//声明缓冲区大小为10的通道,当长度等于10时,再进就会阻塞
ch3 := make(<-chan string)//声明只读通道
ch4 := make(chan<- string)//声明只写通道
ch2 <- "a"//写入chan
val, ok := <- ch2
//or
val := <- ch2//读取chan
close(ch2)//关闭chan
//注意只读的chan不能close
//close以后还可以读取,但不能再写入

从无缓存的 channel 中读取消息会阻塞,直到有 goroutine 向该 channel 中发送消息;

同理,向无缓存的 channel 中发送消息也会阻塞,直到有 goroutine 从 channel 中读取消息。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main
import "fmt"
func main(){
fmt.Println("main start")
ch := make(chan string)
go func(){
ch <- "a"
}()
go func(){
ele <- ch
fmt.Println(ele)
}()
time.Sleep(1* time.Second)
fmt.Println("main end")
}

使用range遍历

1
2
3
4
ch := make(chan int, 10)
for x := range ch{//一直从ch中读取数据直到该ch被close
fmt.Println(x)
}

map类型

map是哈希表的一个实现,这就要求它的每个映射里的key都是唯一的,可以使用==!=来进行判等操作,换句话说key必须是可哈希的

1
2
3
4
5
6
7
8
9
var scores map[string]int//纯声明,此时scores的值为nil,无法赋值
scores1 := map[string]int{"english": 80, "chinese": 85}
scores2 := make(map[string]int)
scores2["english"] = 80//添加元素
scores2["chinese"] = 85
scores2["english"] = 140//更新元素
fmt.Peintln(scores2["english"]) //根据key读取value,如果key不存在则返回这个value的零值
delete(scores2, "english")//根据key删除元素,如果key不存在则静默处理
chinese, ok = scores2["chinese"]//ok表示是否存在

对字典进行循环

1
2
3
4
5
6
7
8
9
10
scores1 := map[string]int{"english": 80, "chinese": 85}
for subject, score := range scores1 {
...
}
for subject := range scores1 {
...
}
for _, score := range scores1 {
...
}

布尔类型

在Go语言中,不同类型间无法比较,因而以下表达式是错误的

1
2
3
4
5
//编译错误的表达式
var male bool = true
if male == 1 {//不能将布尔类型与整数类型进行比较
...
}

控制流语句

if-else

Go要求else ifelse 两边的花括号必须在同一行,且要求条件表达式必须严格返回布尔类型的数据

在if 里可以允许先运行一个表达式,取得变量后,再对其进行判断

1
2
3
if age := 18; age >= 18 {
fmt.Println("已经成年了")
}

switch

switch从第一个判断表达式为true 的case开始执行,不需要break

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package main
import "fmt"
func main(){
var x interface{}
switch i := x.(type) {
case nil:
fmt.Printf("The type of x is %T",i)
case int:
fmt.Printf("The type of x is int")
case func(int) float64:
fmt.Printf("The type of x is func(int)")
case bool, string://多条件匹配
fmt.Printf("The type of x is bool or string")
default:
fmt.Printf("Unknown type")
}
}
//The type of x is <nil>

需要强制执行下一条的时候可以使用fallthrough

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package main 
import "fmt"
func main(){
switch{
case false:
fmt.Println("1")
fallthrough
case true:
fmt.Println("2")
fallthrough
case false:
fmt.Println("3")
}
}
/*
2
3
*/

for

for后面可以接的表达式有:

  • 条件表达式
  • 三个表达式(init; condition; increment)
  • range 表达式
  • 不接表达式
1
2
3
4
5
6
i := 0
sum := 0
for i < 10 {//类似于C中的while
sum += 1
i++
}
1
2
3
4
sum := 0
for i := 0; i < 10; i++ {
sum += i
}
1
2
3
4
arr := [...]string{"xiong", "fang"}
for _, item := range arr {//range返回值为 index,item,在这里不需要index
fmt.Printf("hello, %s \n",item)
}

goto

Go语言的goto语句与标签之间不能有变量声明,否则会编译错误

1
2
3
4
5
//编译错误
goto flag
var say = "This is wrong"
flag:
...

defer延时调用

defer后跟一个表达式,意味着在所处函数执行完之后再调用该表达式

1
2
3
4
5
6
7
func myfunc() {
fmt.Println("B")
}
func main(){
defer myfunc()
fmt.Println("A")
}

defer只是延时调用,变量已经传递过去了,且是反序调用,后进先出

1
2
3
4
5
6
7
8
9
10
11
12
13
func main() {
name := "go"
defer fmt.Println(name)
name = "rust"
defer fmt.Println(name)
name = "c++"
fmt.Println(name)
}
/*
c++
rust
go
*/

defer在return之后调用

1
2
3
4
5
6
7
8
9
10
11
12
13
var name string = "go"
func myfunc() string{
defer func() {
name = "python"
}()
fmt.Println("The name in myfunc is ", name)
return name
}
func main(){
myname := myfunc()
fmt.Println("The name in main is ", name)
fmt.Println("The myname in main is ", myname)
}

select

select 的用法类似于IO多路复用,可以同时监听的多个channel的消息状态

1
2
3
4
5
6
7
8
9
10
select {
case <- ch1:
...
case <- ch2:
...
case ch3 <- 10:
...
default:
...
}
  • select 可以同时监听多个channel的写入或读取
  • 执行select时,若只有一个case通过,则执行这个case块
  • 若有多个case通过,则伪随机挑选一个case执行
  • 若所有case都阻塞,且定义了default模块,则执行default模块。若无default模块则select语句阻塞
  • 使用break会跳出select块

设置超时时间:

1
2
3
4
5
6
7
8
9
10
ch := make(chn struct {})
//finish task while send msg to ch
go doTask(ch)
timeout := time.After(5 * time.Second)//time.After返回一个5s后产生信号的管道
select {
case <- ch:
fmt.Println("task finished.")
case <- timout:
fmt.Println("task timeout.")
}

quite channel:

1
2
3
4
5
6
7
8
9
10
11
msgCh := make(chan struct {})
quitCh := make(chan struct {})
for {
select {
case <- msgCh:
doWork()
case <- quitCh:
finish()
return
}
}

函数

函数可以返回多个值

1
2
3
4
func add (a int, b int) (int,string){
c := a + b
return c, "successfully added"
}

函数的返回值也可以预先定义

1
2
3
4
func ad(a int, b int) (c int) {
c = a + b
return
}

方法

方法能给用户自定义的类型添加新的行为。它和函数的区别在于方法有一个接收者。接收者可以是值,也可以是指针

错误处理

panic函数

1
panic("Some error here")//panic: Some error here

recover函数

recover函数可以捕获异常,恢复程序或做收尾工作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
func set_data(x int) {
defer func(){
//recover()只能在defer域中才能生效
if err := recover(); err != nil {
fmt.Println(err)
}
}()
var arr [10]int
arr[x] = 88//故意制造数组越界
}
func main() {
set_data(20)
fmt.Println("everything is ok")
}
/*output
runtime error: index out of range [20] with length 10
everything is ok
*/

面向对象

struct 结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
type Profile struct {
name, gender string//相同类型的字段可以合并
age int
mother, father *Profile
}
func (person Profile) FmtProfile(){
fmt.Println("name: ",person.name)
fmt.Println("age: ",person.age)
fmt.Println("gender: ",person.gender)
}
func main(){
xf := Profile{name: "熊昉"}//未被赋值的字段会自动赋为零值
xf.gender = "male"
xf.age = 18
xf.FmtProfile()
}

改变对象的方法

1
2
3
func (person *Profile) increase_age() {
person.age += 1
}

用组合的方式实现继承

1
2
3
4
5
6
7
8
9
10
type company struct {
companyName string
companyAddr string
}
type staff struct {
name string
age int
gender string
company//匿名字段
}

接口

接口指定了一个类型应该具有的方法,并由该类型决定如何实现这些方法

1
2
3
4
5
6
7
8
9
type Nokia struct {
name string
}
type Phone interface {
call()
}
func (phone Nokia ) call(){
fmt.Println("I'm a phone called Nokia")
}

空接口

普通的接口都有方法,而空接口没有定义任何方法,因此我们可以说所有类型都至少实现了空接口

对于空接口,其值和类型都是nil

1
2
var i interface{}
fmt.Println("type: %T, value: %v",i,i)//type: <nil>, value: <nil>

不能把空接口类型的对象赋值给一个固定类型,也不能对空接口类型的对象切片

当使用空接口来接收任意类型的参数时,它的静态类型是interface{},但动态类型我们并不知道,因此需要使用类型断言

类型断言

类型断言可以

  • 检查i是否为nil
  • 检查i存储的值是否为某个类型
1
2
3
4
5
var i interface{} = 10
t1, ok := i.(int)
fmt.Println(t1, "-", ok)//10-true
t2, ok := i.(string)
fmt.Println(t2, "-", ok)//-false

Type Switch

在需要区分多种类型的时候,用type switch断言会更简单高效

1
2
3
4
5
6
7
8
9
10
11
12
func findType(i interface{}){
switch x := i.(type) {
case int:
fmt.Println(x, "is int")
case string:
fmt.Println(x, "is string")
case nil:
fmt.Println(x, "is nil")
default:
fmt.Println(x "not type matched")
}
}

类型断言仅能对静态类型为空接口(interface{})的对象进行断言

断言完成后,实际上会返回静态类型为你断言的类型的对象,而原有的静态类型仍是空接口类型

接口实现多态

一个接口在不同对象上的不同表现就是多态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
type Good interface {
settleAccount() int
orderInfo() string
}//定义接口
type Phone struct {
name string
quantity int
price int
}
type FreeGift struct {
name string
quantity int
price int
}
func (phone Phone)settleAccount() int{
return phtone.quantity * phtone.price
}
func (phone Phone) orderInfo() string{
return "你要购买" + strconv.Itoa(phone.quantity) + "个" + phone.name + "计:" +
strconv.Itoa(phone.settleAccount()) + "元"
}
func (gift FreeGift) settleAccount() int{
return 0
}
func (gift FreeGift) orderinfo() string{
return "你要购买" + strconv.Itoa(gift.quantity) + "个" + gift.name + "计:" +
strconv.Itoa(gift.settleAccount()) + "元"
}
//实现了这两个方法后,这两个类型在Go语言看来就都是商品类型了
func calculateAllPrice(goods []Good) int{
var allPrice int
for _,good := range goods{
fmt.Println(good.orderInfo())
allPrice += good.settleAcccount()
}
return allPrice
}

Tag

Tag 可以用来增强结构体的定义,Tag会带上一些元信息,不管转义字符串还是原始字符串都可以用来当Tag

1
2
3
4
5
6
type T struct {
f1 string " f one"
f2 string
f3 string `f three`
f4,f5 int64 `f four and five`
}

Tags可以由键值对组成,通过使用这样的格式可以使用LookUp函数获取键值对的值

1
2
3
type T2 struct {
f string `one:"1" two:"2" blank: ""`
}

Tag获取方式

需引入reflect包,通过TypeOf函数绑定类型,通过FieldByName函数获取对应字段的field

1
2
3
4
5
6
7
t := reflect.TypeOf(T{})
f1, _ := t.FieldByName("f1")
fmt.Println(f1.Tag)//f one
f4, _ := t.FieldByName("f4")
fmt.Println(f4.Tag)//f four and five
f5, _ := t.FieldByName("f5")
fmt.Println(f5.Tag)//f four and five

使用Lookup方法

1
2
3
4
5
t := reflect.TypeOf(T2{})
f, _ := t.FieldByName("f")
fmt.Println(f.Tag)//one:"1" two:"2" blank: ""
v, ok := f.Tag.Lookup("one")
fmt.Println("%s, %t", v, ok)

Get方法只是简单的包装了Lookup,但是丢弃了是否成功的结果

1
2
3
4
func (tag StructTag) Get(key string) string{
v, _ := tag.Lookup(key)
return v
}

进阶语法

反射

先看维基百科上的定义

在计算机科学中,反射是指计算机程序在运行时可以访问、检测和修改它本身状态或行为的一种能力。

Go语言圣经:

Go 语言提供了一种机制在运行时更新变量和检查它们的值、调用它们的方法,但是在编译时并不知道这些变量的具体类型,这称为反射机制

reflect.Value类型和reflect.Type类型

1
2
3
4
var x float64 = 3.4
fmt.Println("type:",reflect.TypeOf(x))//type: float64
//在reflect.TypeOf的函数签名里包含一个空接口
fmt.Println("value:",reflect.ValueOf(x))//value: 3.4

kind方法

reflect.Valuereflect.Type都有一个名为Kind的方法,它会返回一个常量,表示底层数据的类型

Value类型也有一些类似于IntFloat的方法,用来提取底层的数据

1
2
3
4
5
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())

Slice()

Slice()跟其他类型转换的函数不一样,它返回的还是reflect.Value反射对象

Interface方法

可以根据一个reflect.Value类型的变量恢复其接口类型的值,事实上,这个方法会把type和value信息打包并填充到一个接口变量中,然后返回

其函数声明如下:

1
func (v Value) Interface() interface{}

CanSet方法

1
2
3
var x float64 = 34
v := reflect.ValueOf(x)//传递的是x的拷贝,而非x本身
fmt.Println("settability of v:", v.CanSet())//settability of v: false

传递指针则可写

1
2
3
4
5
6
7
var x float64 = 3.4
p := reflect.ValueOf(&x)
v := p.Elem()
fmt.Println("settability of v:", v.CanSet())//settability of v: true
v.SetFloat(7.1)
fmt.Println(v.Interface())//7.1
fmt.Println(x)//7.1

json包

1
2
3
4
5
6
7
8
9
10
package main
import (
"fmt"
"encoding/json"
)
func main(){
mapA := map[string] int{"apple": 5, "lettuce" :7}
mapB,_:=json.Marshal(mapA)//编码
fmt.Println(string(mapB))
}
1
2
3
4
5
6
7
8
package main
import (
"fmt"
"encoding/json"
)
type response struct{
PageNumber int `json:"page"`

数据类型

byte外的所有数字字面值允许使用类型后缀,如57u8

在debug模式中,整形溢出会导致程序panic。而release模式中,则会进行回环(Wrapping

如果确实需要整形溢出,可以使用Wrapping类型

1
2
3
let max = Wrapping(i32::MAX);//用标准库的Wrapping<T>结构体包装基本数据类型的数字
//或者直接调用.wrapping_***(...)成员方法来完成算术运算
assert_eq!(i32::MAX.wrapping_add(2), i32::MIN+1);
1
2
3
4
5
6
7
8
let a = 123_4; //整数中可以出现下划线
let tup:(i32,f64,u8) = (500,6.4,1);//元组可以包含不同种类的数据
//tup.0等于500。。。
let (x,y,z) = tup;//解构元组

let a = [1,2,3,4,5];//数组包含同类型数据
let a: [i32;5] = [1,2,3,4,5];//[元素类型;元素数量]
//当索引超出了下标范围时会发生一个运行时错误

字符串

str是Rust核心语言类型,常常以引用的形式出现(&str)

凡是用双引号包括的字符串常量的类型都是&str

String 则有更完善的功能

1
2
let s1 = String::from("Hello");
let s2 = &s1[..];//从String类型转为&str类型

可以用+号运算符进行简单的拼接

1
2
3
let s1 = String::from("Hello,");
let s2 = String::from("world!");
let s3 = s1 + &s2;//s1 在此之后不可用

+运算符使用了add函数,这个函数签名看起来像这样

1
2
3
fn add(self, s: &str) -> String {
...
}

之所以能在add调用中使用&s2是因为&String可以被强制转换成&str

对于更为复杂的字符串链接,可以使用format!宏:

1
2
3
4
5
let s1 = String::from("tic");
let s2 = String::from("tac");
let s3 = String::from("toe");
let s = format!("{}-{}-{}",s1,s2,s3);
//format!与println!的工作原理相同,不同之处是其返回一个带有结果内容的String

使用parse或turbo fish语法实现从字符串到其他类型的转换:

1
2
3
4
5
6
7
8
9

//只要目标类型实现了FromStr特性
fn main(){
let parsed: i32 = "5".parse().unwrap();
let turbo_parsed = "10".parse::<i32>().unwrap();

let sum = parsed + turbo_parsed;
println!{"Sum: {:?}",sum};
}

内部表现

String是一个Vec<u8>的封装,而Unicode是使用两个字节表示一个字,因此String不支持下标访问

结构体

元组常用于非定义的多值传递,而结构体用于定义对象规范,结构体的每个成员叫做“字段”

1
2
3
4
5
6
7
8
//一个结构体定义
struct Site{
domain: String,
name: String,
nation: String,
found: u32
//每个字段定义后用","分隔
}
1
2
3
4
5
6
7
8
//结构体实例
let mysite = Site{
//key: value 语法
domain: String::from("ajsoabk.xyz"),
name: String::from("Ajsoabk"),
nation: String::from("China"),
found: 2020
};//记得分号
1
2
3
4
5
6
7
8
9
10
11
12
13
let domain = String("ajsoabk.xyz");
let name = String("Ajsoabk");
let mysite = Site{
domain,//有同名变量时可以简化
name,//等同于name: name
nation: String:from("China"),
found: 2020
};
//结构体更新语法
let newsite = Site{
domain: String("www.ajsoabk.xyz"),
..mysite
};//这种语法需要至少重新设定一个字段的值

元组结构体

形式是元组的结构体

1
2
3
4
5
6
7
struct Color(u8,u8,u8);
struct Point(f64,f64);

let black = Color(0,0,0);
let origin = Point(0.0,0.0);
println!("black = ({},{},{})",black.0,black.1,black.2);
println!("origin = ({},{})",origin.0,origin.1);

输出结构体

1
2
3
4
5
6
7
8
9
10
#[derive(Debug)]//导入调试库
struct Rectangle{
width: u32,
height: u32,
}
fn main(){
let rect1= Rectangle{width:30,height:50};
println!("rect1 is {:?}",rect1);//使用{:?}占位符输出结构体
println!("rect1 is {:#?}",rect1)://使用{:#?}占位符分行输出结构体
}

结构体方法

1
2
3
4
5
6
7
8
9
10
11
12
13
struct Rectangle{
width: u32,
height:32,
}
impl Rectangle{
fn area(&self) -> u32{//结构体方法的第一个参数必须是&self,不需要声明类型
self.width * self.height
}
}
fn main(){
let ret1 = Rectangle {width : 30,height: 50};
println!("rect1's area is {}",rect1.area());
}

结构体关联函数

结构体关联函数与结构体方法的区别是结构体关联函数在impl块中却没有&self 参数

这种函数不依赖实例,但却需要声明是在哪个impl块中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#[derive(Debug)]
struct Rectangle{
width: u32,
height: u32,
}
impl Rectangle{
fn create(width: u32,height: u32) -> Rectangle{
Rectanlge{width,height}
}
}
fn main(){
let rect = Rectangle::create(30,50);
println!("{:?}",rect);
}

impl块可以写多次,相当于将其拼接

1
2
3
4
5
6
7
8
//对于非枚举类,需要设置缺省情况
fn main(){
let t = "abc";
match t {
"abc" => println!("Yes"),
_ => {},
}
}

Option、Result与kind

Option类包含None及Some,用于可能有空值的情况

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
fn check_division(dividend: i32,divisor: i32) -> Option<i32>{
if divisor == 0{
None
}
else {
Some(dividend / divisor)
}
}
fn try_division(dividend: i32,divisor: i32){
match checked_division(dividend,divisor){
None => println!("{} / {} failed!",dividend,divisor);
Some(quotient) => {
println!("{} / {} = {}",dividend, divisor, quotient)
},
}
}
fn main(){
try_division(4,2);
try_division(1,0);
}

Result类则可以包含相关错误信息,还有专门的?操作符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
fn f(i: i32) -> Result<i32, bool> {
if i >= 0 { Ok(i) }
else { Err(false) }
}
fn g(i: i32) -> Result<i32, bool> {
let t = f(i)?;//在Result出现异常的时候直接返回异常
Ok(t)
}
fn main(){
let r = g(10000);
if let Ok(v) = r{
println!("Ok: g(10000) = {}", v);
} else {
println!("Err");
}
}

Result类还有kind方法可以确定错误类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
use std::io;
use std::io::Read;
use std::fs::File;
fn read_text_from_file(path: &str) -> Result<String, io::Error>{
let mut f = File::open(path)?;
let mut s = String::new();
f.read_to_string(&mut s)?;
Ok(s)
}
fn main(){
let str_file = read_text_from_file("hello.txt");
match str_file{
Ok(s) => prinln!("{}",s);
Err(e) => {
match e.kind(){//根据错误类型进行相应处理
io::ErrorKind::NotFound => {
println!("No such file");
},
_ => {
println!("Cannot read the file");
}
}
}
}
}

vector

1
2
3
4
5
6
7
8
9
let v= vec![1,2,3,4,5];//用vec!宏进行初始化
let mut v:Vec<i32> = Vec::new();//新建vector变量
v.push(5)
println!("The third element is {}",v[0]);//访问下标为0的位置上的元素,若超出则会崩溃
//或者使用get方法,可以自己选择超出后的处理方法
match v.get(2) {
Some(i) => println!("The third element is {}",i),
None => println!("There is no third element."),,
}

控制流语句(if,while,for,loop,if let, match)

lf-else 作为表达式

1
2
3
let a = 3;
let b = 4;
println!("the max num in {} and {} is {}",a,b,if a > b {a} else {b});

使用loop查找

1
2
3
4
5
6
7
8
9
let s = ['X','i','o','n','g','F','a','n','g'];
let mut i = 0;
let location = loop {
if(s[i] == 'F'){
break i
}
i += 1;
};
println!("The location of \'F\' is {}",location);

match 和if let

1
2
3
4
5
6
fn plus_one(x: Option<i32>) -> Option<i32> {
match x {
None => None,
Some(i) => Some(i + 1),//匹配的同时绑定i
}
}

匹配必须穷尽

1
2
3
4
5
let some_u8_value = Some(0u8);
match some_u8_value {
Some(1) => println!("one"),
_ => (),//所有剩余情况的匹配
}

可以使用if let 来进行匹配且无需穷尽

1
2
3
4
5
6
fn plus_one(x:Option<i32>) -> Option<i32> {
if let Some(i) = x {
return Some(i+1);
}
None
}

所有权机制

  • Rust中的每个值都有一个变量,称为其所有者
  • 一次只能有一个所有者
  • 当所有者不在程序运行范围内时,该值将被删除

移动

1
2
3
4
let x = 5;
let y = x;
//此时栈中有两个值5,因为int是基本数据类型,基本数据类型具有Copy特性
//Copy特性保证其对象在被赋值给其他对象后仍然可用

整型、布尔类型、浮点型、字符类型和仅包含以上类型的元组是基本数据类型

但如果发生交互的数据在堆中就是另外一种情况

1
2
3
let s1 = String::from("Hello");//"Hello"可以认为是类似于长度不确定的数据,需要在堆中存储
let s2 = s1;//由于两者都指向堆中变量,因此为了防止两次释放,s1被赋值给s2后,s1已经无效了
println!("{} World!",s1); //错误!s1已经失效

克隆

1
2
3
let s1 = String::from("Hello");
let s2 = s1.clone();
println!("s1 = {}, s2 = {}",s1,s2);

涉及函数的所有权机制

如果讲变量当作参数传入函数,那么它和移动的效果是一样的

被当作函数返回值的变量所有权将会被移动出函数并返回到调用函数的地方,而不会直接被无效释放

引用与租借

1
2
3
let s1 = String::from("Hello");
let s2 = &s1;
println!("s1 is {}, s2 is {}",s1,s2);

&可以取变量的引用,引用并没有在栈中复制变量的值

引用不会获得值的所有权。引用只能租借值的所有权,引用本身也是一个类型并具有一个值,这个值记录的是别的值所在的位置,但引用不具有所指值的所有权

1
2
3
4
5
//一段不正确的代码
let s1 = String::from("Hello");
let s2 = &s1;
let s3 = s1;
println!("{}",s2);//错误,所有权已经转给s3,s2需要重新从s3租借所有权
1
2
3
4
5
let s1 = String::from("Hello");
let mut s2 = &s1;
let s3 = s1;
s2 = &s3;
println!("{}",s2);//正确

如果尝试利用租借来的权力来修改数据会被阻止

可变引用

可以使用可变引用来修改数据

1
2
3
4
let mut s1 = String::from("Hello");
let s2 = &mut s1;
s2.push_str(" World!");
println!("{}",s2);

可变引用不允许多重引用(不管是可变还是非可变)

1
2
3
4
5
//一段不正确的代码
let mut s = String::from("Hello");
let r1 = &mut s;
let r2 = &mut s;//错误,可变引用不允许多重引用
println!("{},{}",r1,r2);

主要是为了防止在并发状态下发生数据访问碰撞

错误的悬垂引用

1
2
3
4
5
6
7
fn main(){
let reference_to_nothing = dangle();
}
fn dangle() -> &String{
let s =String::from("Hello");
&s//此时s已经被释放,但s的引用却被返回,这个引用所指向的值已经不存在
}

编译器会发现这种错误

Rust 组织管理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
mod nation{
pub mod government{
pub fn govern(){}//pub公开路径
}
mod congress{
pub fn legislate(){}
}
mod court{
fn judicial(){
super::congress::legislate();//super进入上一级
}
}
pub use congress::legislate;//pub use使外部代码也能直接使用新路径
}
use nation::{government::govern,legislate};//嵌套路径
use std::io::{self, Write};//可用self指定自身
use std::collections::*;//用*指定所有公有项

Rust泛型与特性

1
2
3
4
5
6
7
8
9
10
11
12
struct Point<T,U> {
x:T,
y:U,
}
impl<T,U> Point<T,U> {
fn mixup<V,W>(self,other: Point<V,W>) -> Point<T,W>{
Point{
x: self.x,
y: other.y,
}
}
}

一个类可以实现多个特性,每个impl块只能怪为一个类实现一个特性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
trait Comparable {
fn compare(&self, object: &Self) -> i8;//描述Comparable特性
}
fn max<T: Comparable> (array: &[T]) -> &T {
let mut max_index = 0;
let mut i = 1;
while i< array.len() {
if array[i].compare(&array[max_index]) > 0{
max_index = i;
}
i += 1;
}
&array[max_index]
}
impl Comparable for f64 {
fn compare(&self, object: &f64) -> i8{
if &self > &object {1}
else if &self == &object {0}
else {-1}
}
}
fn main(){
let arr = [1.0,3.0,5.0,4.0,2.0];
println!("maximum of arra is {}",max(&arr));
}

默认特性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
trait Descriptive{
fn describe(&self) -> String {
String::from("[Object]")
}
}
struct Person {
name: String,
age: u8
}
impl Descriptive for Person{
fn describe(&self) -> String {
format!("{} {}",self.name,self.age)
}
}
fn main(){
let cali = Person{
name: String::from("Cali"),
age: 24
};
println!("{}",cali.describe());
}

所有动作都需要感受臀部发力!!!

动作 技巧 目的 肌群 进阶练习
平板直抬腿 注意抬起加速
注意保持直腿及上身稳定
提高爆发力,加快大腿抓地速度 臀大肌及大腿后侧肌群 双腿离地
行进箭步蹲 注意动作完成度及离心加速
注意上身直立及整体稳定
注意后腿膝盖不要用力磕地,点到为止
提高爆发力,训练抓地速度 臀大肌及股四头肌 负重
平地提踵 注意高抬慢放,脚后跟不要触地 提高踝关节稳定性及压脚掌动作的质量 腓肠肌等小腿肌群 负重、垫高前脚掌
坐姿交替直抬腿 注意顶峰收缩及高抬慢放 提高直腿稳定性及柔韧性 股四头肌,腹肌 双腿离地
单脚提踵 同平地提踵,尤其注意稳定性维持 针对性提高单脚脚掌力量 腓肠肌等小腿肌群 负重、垫高前脚掌
单脚侧蹲 所抬脚不要触地,尤其注意稳定性维持 针对性提高单腿侧向稳定性 臀大肌、股四头肌等肌群 已经够难了
靠墙静蹲 注意上身贴墙,腿部大约成直角,手不要放在腿上防止给膝盖更大压力 提高腿部耐力,保护膝盖 大部分大腿肌群 加长时间