Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give multiple function parameters the same type?

Tags:

rust

When declaring a function in Go, one can give multiple parameters the same type:

func test(a, b, c uint8) { }

Does Rust have a way to give multiple parameters the same type without explicitly specifying each one of them manually?

This doesn't seem to work:

fn test(a, b, c: u8) { }
like image 815
typos Avatar asked Dec 19 '17 19:12

typos


1 Answers

Simply:

fn test(a: u8, b: u8, c: u8) {}

There is no short-cut syntax available if you want to name each individually.

If you do not care for individual names:

fn test(a: &[u8; 3]) {}

And if the number of items ought to be dynamic:

fn test(a: &[u8]) {}

I would note that, personally, I generally find the idea of passing multiple parameters of the same type to a function a rather brittle design in the absence of named parameters.

Unless those parameters are interchangeable, in which case swapping them doesn't matter, then I recommend avoiding such function signatures. And by extension, I do not see the need for a special syntax to accommodate the brittleness.

In exchange, Rust features tuple structs: struct X(u8);, allowing one to quickly whip up new types to represent new concepts, rather than fall into Primitive Obsession.

like image 79
Matthieu M. Avatar answered Oct 19 '22 01:10

Matthieu M.