fork/rust

git clone https://git.julia.blue/fork/rust

borsAuto merge of #103046 - JanBeh:PR_clarify_cmp_terminology, r=workingjubilee3bcad65fbf6

master
2.4 KiB71 linesraw
1Per [RFC 401][rfc401], if you have a function declaration `foo`:
2
3```
4struct S;
5
6// For the purposes of this explanation, all of these
7// different kinds of `fn` declarations are equivalent:
8
9fn foo(x: S) { /* ... */ }
10extern "C" {
11    fn foo(x: S);
12}
13impl S {
14    fn foo(self) { /* ... */ }
15}
16```
17
18the type of `foo` is **not** `fn(S)`, as one might expect.
19Rather, it is a unique, zero-sized marker type written here as `typeof(foo)`.
20However, `typeof(foo)` can be _coerced_ to a function pointer `fn(S)`,
21so you rarely notice this:
22
23```
24let x: fn(S) = foo; // OK, coerces
25```
26
27The reason that this matter is that the type `fn(S)` is not specific to
28any particular function: it's a function _pointer_. So calling `x()` results
29in a virtual call, whereas `foo()` is statically dispatched, because the type
30of `foo` tells us precisely what function is being called.
31
32As noted above, coercions mean that most code doesn't have to be
33concerned with this distinction. However, you can tell the difference
34when using **transmute** to convert a fn item into a fn pointer.
35
36This is sometimes done as part of an FFI:
37
38```
39extern "C" fn foo(userdata: Box<i32>) {
40    /* ... */
41}
42
43unsafe {
44    let f: extern "C" fn(*mut i32) = transmute(foo);
45    callback(f);
46}
47```
48
49Here, transmute is being used to convert the types of the fn arguments.
50This pattern is incorrect because the type of `foo` is a function **item**
51(`typeof(foo)`), which is zero-sized, and the target type (`fn()`)
52is a function pointer, which is not zero-sized.
53This pattern should be rewritten. There are a few possible ways to do this:
54
55- change the original fn declaration to match the expected signature,
56  and do the cast in the fn body (the preferred option)
57- cast the fn item of a fn pointer before calling transmute, as shown here:
58
59    ```
60    let f: extern "C" fn(*mut i32) = transmute(foo as extern "C" fn(_));
61    let f: extern "C" fn(*mut i32) = transmute(foo as usize); // works too
62    ```
63
64The same applies to transmutes to `*mut fn()`, which were observed in practice.
65Note though that use of this type is generally incorrect.
66The intention is typically to describe a function pointer, but just `fn()`
67alone suffices for that. `*mut fn()` is a pointer to a fn pointer.
68(Since these values are typically just passed to C code, however, this rarely
69makes a difference in practice.)
70
71[rfc401]: https://github.com/rust-lang/rfcs/blob/master/text/0401-coercions.md