#References question

17 messages · Page 1 of 1 (latest)

old ermine
#

"bye" is a string literal and therefore it is stored in the binary. it can be returned because:

  1. the lifetime of a string literal is 'static as its type is &'static str
  2. &str is covariant, therfore the lifetime can be shortened to the appropriate length
#

yes, because the data is embedded in the binary, not in the stack

#

?godbolt

pub fn main() {
    print!("{}", test("no"));
}

fn test(_p: &str) -> &str {
    "bye"
}
misty lintelBOT
#
<&T as core::fmt::Display>::fmt:
        mov     rdx, rsi
        mov     rax, qword ptr [rdi]
        mov     rsi, qword ptr [rdi + 8]
        mov     rdi, rax
        jmp     qword ptr [rip + <str as core::fmt::Display>::fmt@GOTPCREL]

example::main:
        sub     rsp, 88
        lea     rax, [rip + .L__unnamed_1]
        mov     qword ptr [rsp + 24], rax
        mov     qword ptr [rsp + 32], 3
        lea     rax, [rsp + 24]
        mov     qword ptr [rsp + 8], rax
        lea     rax, [rip + <&T as core::fmt::Display>::fmt]
        mov     qword ptr [rsp + 16], rax
        lea     rax, [rip + .L__unnamed_2]
        mov     qword ptr [rsp + 40], rax
        mov     qword ptr [rsp + 48], 1
        mov     qword ptr [rsp + 72], 0
        lea     rax, [rsp + 8]
        mov     qword ptr [rsp + 56], rax
        mov     qword ptr [rsp + 64], 1
        lea     rdi, [rsp + 40]
        call    qword ptr [rip + std::io::stdio::_print@GOTPCREL]
        add     rsp, 88
        ret

.L__unnamed_1:
        .ascii  "bye"

.L__unnamed_2:
        .quad   1
        .zero   8
```Note: only public functions (`pub fn`) are shown
old ermine
#

so it lives for as long as the program is alive

#

i guess you could say that the owner of "bye" is the binary

#

they are somewhat separate concepts

#

the "lives only as long as it needs to" requires you to understand covariance

#

yeah just learn that later

#

after the book (i presume you are reading it right now)

old ermine
#

regardless of the lifetime "no" has, it will still work because the lifetime of the return type is derived from the lifetime of p, of which is was returned

#

(this concept also applies earlier)

tight totem
#

also, string literals are not special here other than having a short syntax; you can get a &'static reference to anything that can be constructed at compile time

#

?play

fn foo() -> &'static [u8; 4] {
    &[1, 2, 3, 4]
}
misty lintelBOT