rust-lang / rust-lang/rfcs

Empower users to control the instantiation of the function body

Open
#3,357 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Markdown
Stars
6.6k
Forks
1.7k
Avg merge
16h 14m
Merged PRs (30d)
1

Description

fn func<T:Trait>(v:T){
}

Currently, we can only do the behavior the Trait empowers us to, i.e. the type is opaque in the function body, we only know it implements the trait and can do everything the Trait can do. Consider we want to specialize the behavior if T is a particular type.

In C++, we do those things as the following

template<class T>
requires Trait<T>
void fun(T){
   if constexpr(std::is_same_v<T,std::string>){
      // instantiate this part if the type is String
  }else{
    // otherwise, instantiate this part
  }
}

This permits us to control the instantiation of the function body without being overhead in runtime. In Rust, the possible way must cost in run-time.

enum TypeEnum{
   is_i32(i32),
   is_string(String)
}
trait TypeId{
    fn to_type_enum(self)->TypeEnum;
}
impl TypeId for i32{
    fn to_type_enum(self)->TypeEnum{
          TypeEnum::is_i32(self)
    }
}
impl TypeId for String{
    fn to_type_enum(self)->TypeEnum{
          TypeEnum::is_i32(self)
    }
}
fn func<T:Trait + TypeId>(v:T){
   let r = v.to_type_enum();
   match r {
     TypeEnum::is_i32(x)=>{}  
     TypeEnum::is_string(x)=>{}
   }
}

The match pattern can be used to imitate the function brought by if constexpr to a certain degree, however, the latter is zero-cost while the former has a run-time cost.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the issue's Rust and C++ examples, then examine how Rust currently handles generic bounds and compile-time type specialization. No files, tests, or entry points are named; a useful outcome would first define the language semantics and zero-runtime-cost requirements before proposing an RFC.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.