Skip to content

Add associated consts to f32, f64 for mathematical constants #210

@pommicket

Description

@pommicket

Proposal

Problem statement

Currently, to use mathematical constants such as π, you need to use std::f32::consts::PI.
This proposal is for adding associated constants to the f32 and f64 types so that the constants could be accessed with just f32::PI for example.

Motivation, use-cases

  1. std::f32::consts::PI is quite long. It takes a while to type out, and makes code difficult to read if written out in full everywhere.
    Consider
    assert_eq!(std::f32::consts::FRAC_PI_4.sin(), std::f32::consts::FRAC_1_SQRT_2);
    vs
    assert_eq!(f32::FRAC_PI_4.sin(), f32::FRAC_1_SQRT_2);
    You can always do something like use std::f32::consts as f32c; but it would be nice for a shorter path to be included in the standard library.
  2. I think this is where first-time users of Rust would expect mathematical constants to be. I know that when I first wanted to use π in a rust program, I wrote out f32::PI and to my disappointment it didn't work and I had to do an internet search to find out the correct path.
  3. NAN, INFINITY, etc. are associated constants, and it feels inconsistent to me for f32::NAN to exist, but not f32::PI.

Solution sketches

I have implemented this on my fork: rust-lang/rust@master...pommicket:rust:shorter-paths-for-float-consts

Links and related work

What happens now?

This issue is part of the libs-api team API change proposal process. Once this issue is filed the libs-api team will review open proposals in its weekly meeting. You should receive feedback within a week or two.

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-libs-apiapi-change-proposalA proposal to add or alter unstable APIs in the standard libraries

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions