Skip to content

Printing function address is confusing due to per-function ZST "singleton type" #75239

Closed
@tesuji

Description

@tesuji

I tried this code: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=61fe688172759b7756e84751557e39ea

use std::mem::size_of;
fn bar() -> usize { 42 }
type Left = [u8; 16];
println!("{:p}", size_of::<Left>);
println!("{:p}", bar);

I expected to see this happen:
The compilation succeed or guide me to

  • (1) cast the fn to *const () with as.
  • (2) borrow the fn: &size_of::<Left>. But in this case the addresses printed are the same (what?).
    0x55867559f000
    0x55867559f000
    

Instead, this happened:
Cryptic error message:

error[E0277]: the trait bound `fn() -> usize {std::mem::size_of::<[u8; 16]>}: std::fmt::Pointer` is not satisfied
 --> src/main.rs:6:22
  |
6 |     println!("{:p}", size_of::<Left>);
  |                      ^^^^^^^^^^^^^^^ the trait `std::fmt::Pointer` is not implemented for `fn() -> usize {std::mem::size_of::<[u8; 16]>}`
  |
  = note: required by `std::fmt::Pointer::fmt`
  = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

There is impl<usize> Pointer for fn() -> usize: https://doc.rust-lang.org/nightly/std/fmt/trait.Pointer.html#impl-Pointer-3 .
It took me minutes before I found the workaround. But it still surprised me.

Meta

rustc --version --verbose:

rustc 1.47.0-nightly (22ee68dc5 2020-08-05)
binary: rustc
commit-hash: 22ee68dc586440f96b76b32fbd6087507c6afdb9
commit-date: 2020-08-05
host: x86_64-unknown-linux-gnu
release: 1.47.0-nightly
LLVM version: 10.0

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.D-terseDiagnostics: An error or lint that doesn't give enough information about the problem at hand.E-mediumCall for participation: Medium difficulty. Experience needed to fix: Intermediate.E-mentorCall for participation: This issue has a mentor. Use #t-compiler/help on Zulip for discussion.T-langRelevant to the language team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions