Giter Club home page Giter Club logo

blog's Introduction

blog

blog's People

Contributors

yyvanyang avatar

Watchers

 avatar  avatar

blog's Issues

6.2. 基于指针对象的方法

想要调用指针类型方法(*Point).ScaleBy,只要提供一个Point类型的指针即可,像下面这样。

r := &Point{1, 2}
r.ScaleBy(2)
fmt.Println(*r) // "{2, 4}"

或者这样:

p := Point{1, 2}
pptr := &p
pptr.ScaleBy(2)
fmt.Println(p) // "{2, 4}"

或者这样:

p := Point{1, 2}
(&p).ScaleBy(2)
fmt.Println(p) // "{2, 4}"

不过后面两种方法有些笨拙。幸运的是,go语言本身在这种地方会帮到我们。如果接收器p是一个Point类型的变量,并且其方法需要一个Point指针作为接收器,我们可以用下面这种简短的写法:

p.ScaleBy(2)

编译器会隐式地帮我们用&p去调用ScaleBy这个方法。这种简写方法只适用于“变量”,包括struct里的字段比如p.X,以及array和slice内的元素比如perim[0]。我们不能通过一个无法取到地址的接收器来调用指针方法,比如临时变量的内存地址就无法获取得到:

Point{1, 2}.ScaleBy(2) // compile error: can't take address of Point literal

但是我们可以用一个Point这样的接收器来调用Point的方法,因为我们可以通过地址来找到这个变量,只要用解引用符号来取到该变量即可。编译器在这里也会给我们隐式地插入*这个操作符,所以下面这两种写法等价的:

pptr.Distance(q)
(*pptr).Distance(q)

这里的几个例子可能让你有些困惑,所以我们总结一下:在每一个合法的方法调用表达式中,也就是下面三种情况里的任意一种情况都是可以的:

不论接收器的实际参数和其形式参数是相同,比如两者都是类型T或者都是类型*T:

Point{1, 2}.Distance(q) //  Point
pptr.ScaleBy(2)         // *Point

或者接收器实参是类型T,但接收器形参是类型*T,这种情况下编译器会隐式地为我们取变量的地址:

p.ScaleBy(2) // implicit (&p)

或者接收器实参是类型*T,形参是类型T。编译器会隐式地为我们解引用,取到指针指向的实际变量:

pptr.Distance(q) // implicit (*pptr)

如果命名类型T(译注:用type xxx定义的类型)的所有方法都是用T类型自己来做接收器(而不是*T),那么拷贝这种类型的实例就是安全的;调用他的任何一个方法也就会产生一个值的拷贝。比如time.Duration的这个类型,在调用其方法时就会被全部拷贝一份,包括在作为参数传入函数的时候。但是如果一个方法使用指针作为接收器,你需要避免对其进行拷贝,因为这样可能会破坏掉该类型内部的不变性。比如你对bytes.Buffer对象进行了拷贝,那么可能会引起原始对象和拷贝对象只是别名而已,实际上它们指向的对象是一样的。紧接着对拷贝后的变量进行修改可能会有让你有意外的结果。

译注: 作者这里说的比较绕,其实有两点:

不管你的method的receiver是指针类型还是非指针类型,都是可以通过指针/非指针类型进行调用的,编译器会帮你做类型转换。
在声明一个method的receiver该是指针还是非指针类型时,你需要考虑两方面的因素,第一方面是这个对象本身是不是特别大,如果声明为非指针变量时,调用会产生一次拷贝;第二方面是如果你用指针类型作为receiver,那么你一定要注意,这种指针类型指向的始终是一块内存地址,就算你对其进行了拷贝。熟悉C或者C++的人这里应该很快能明白。

命令行参数

1.2. 命令行参数

os包以跨平台的方式,提供了一些与操作系统交互的函数和变量。程序的命令行参数可从os包的Args变量获取;os包外部使用os.Args访问该变量。

os.Args变量是一个字符串(string)的切片(slice)

和大多数编程语言类似,区间索引时,Go言里也采用左闭右开形式, 即,区间包括第一个索引元素,不包括最后一个, 因为这样可以简化逻辑。

比如s[m:n]这个切片,0 ≤ m ≤ n ≤ len(s),包含n-m个元素。

os.Args的第一个元素,os.Args[0], 是命令本身的名字;其它的元素则是程序启动时传给它的参数。s[m:n]形式的切片表达式,产生从第m个元素到第n-1个元素的切片,下个例子用到的元素包含在os.Args[1:len(os.Args)]切片中。如果省略切片表达式的m或n,会默认传入0或len(s),因此前面的切片可以简写成os.Args[1:]。

Floating point precision

In JavaScript, computations with numbers don’t always produce precise results. For example:

0.1 + 0.2
0.30000000000000004
To understand why, we need to explore how JavaScript represents floating point numbers internally. It uses three integers to do so, as described in tbl. 5.

Table 5: Internally, JavaScript uses three integers to represent floating point numbers. They take up a total of 64 bits of storage (double precision).

Component Size Integer range
sign 1 bit [0, 1]
fraction 52 bits [0, 252−1]
exponent 11 bits [−1023, 1024]

The floating point number represented by these integers is computed as follows:

(–1)sign × 0b1.fraction × 2exponent

To make further discussions easier, we simplify this representation:

  • Instead of base 2 (binary), we use base 10 (decimal), because that’s what most people are more familiar with.
  • The fraction is a natural number that is interpreted as a fraction (digits after a point). We switch to a mantissa, an integer that is interpreted as itself. As a consequence, the exponent is used differently, but its fundamental role doesn’t change.
  • As the mantissa is an integer (with its own sign), we don’t need a separate sign, anymore.

The new representation works like this:

mantissa × 10exponent

Let’s try out this representation for a few floating point numbers.

  • For the integer −123, we mainly need the mantissa:

-123 * (10 ** 0)
-123

  • For the number 1.5, we imagine there being a point after the mantissa. We use a negative exponent to move that point one digit to the left:

15 * (10 ** -1)
1.5

  • For the number 0.25, we move the point two digits to the left:

25 * (10 ** -2)
0.25

Representations with negative exponents can also be written as fractions with positive exponents in the denominators:

15 * (10 ** -1) === 15 / 10
true
25 * (10 ** -2) === 25 / 100
true

These fractions help with understanding why there are numbers that our encoding cannot represent:

  • 1/10 can be represented. It already has the required format: a power of 10 in the denominator.
  • 1/2 can be represented as 5/10. We turned the 2 in the denominator into a power of 10, by multiplying numerator and denominator with 5.
  • 1/4 can be represented as 25/100. We turned the 4 in the denominator into a power of 10, by multiplying numerator and denominator with 25.
  • 1/3 cannot be represented. There is no way to turn the denominator into a power of 10. (The prime factors of 10 are 2 and 5. Therefore, any denominator that only has these prime factors can be converted to a power of 10, by multiplying both numerator and denominator with enough twos and fives. If a denominator has a different prime factor, then there’s nothing we can do.)

To conclude out excursion, we switch back to base 2:

  • 0.5 = 1/2 can be represented with base 2, because the denominator is already a power of 2.
  • 0.25 = 1/4 can be represented with base 2, because the denominator is already a power of 2.
  • 0.1 = 1/10 cannot be represented, because the denominator cannot be converted to a power of 2.
  • 0.2 = 2/10 cannot be represented, because the denominator cannot be converted to a power of 2.

Now we can see why 0.1 + 0.2 doesn’t produce a precise result: Internally, neither of the two operands can be represented precisely.

The only way to compute precisely with decimal fractions is by internally switching to base 10. For many programming languages, base 2 is the default and base 10 an option. For example, Java has the class BigDecimal and Python has the module decimal. There are tentative plans to add something similar to JavaScript: The ECMAScript proposal “Decimal” is currently at stage 0.

reference

http://exploringjs.com/impatient-js/ch_numbers.html#background-floating-point-precision

Functions for converting numbers to integers

Functions for converting numbers to integers. Note how things change with negative numbers, because “larger” always means “closer to positive infinity”.

  -2.9 -2.5 -2.1 2.1 2.5 2.9
Math.floor -3 -3 -3 2 2 2
Math.ceil -2 -2 -2 3 3 3
Math.round -3 -2 -2 2 3 3
Math.trunc -2 -2 -2 2 2 2

Converting values to numbers.

x Number(x)
undefined NaN
null 0
boolean false → 0, true → 1
number x (no change)
string '' → 0
  other → parsed number, ignoring leading/trailing whitespace
object configurable (e.g. via .valueOf())

1.6. 并发获取多个URL

当一个goroutine尝试在一个channel上做send或者receive操作时,这个goroutine会阻塞在调用处,直到另一个goroutine从这个channel里接收或者写入值,这样两个goroutine才会继续执行channel操作之后的逻辑。在这个例子中,每一个fetch函数在执行时都会往channel里发送一个值(ch <- expression),主函数负责接收这些值(<-ch)。这个程序中我们用main函数来接收所有fetch函数传回的字符串,可以避免在goroutine异步执行还没有完成时main函数提前退出。

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.