Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Performing type conversions


D is a strongly typed language, which means converting between types often has to be done explicitly. The language's built-in cast operator only works when the types are already mostly compatible, for example int to short, or in cases where the user has defined an opCast function. This doesn't cover the very common need of converting strings to integers and vice versa. That's where Phobos' std.conv module is helpful.

How to do it…

Now it's time to perform type conversions by executing the following steps:

  1. Import std.conv.

  2. Use the to function as follows:

    import std.conv;
    auto converted = to!desired_type(variable_to_convert);

    This is pretty simple, and it works for a lot of types.

  3. To convert a string to an integer, use the following line of code:

    auto a = to!int("123"); // a == 123

That's all you have to do!

How it works…

The std.conv.to function strives to be a one-stop shop for type conversions. The to function isn't just one function. It is actually a family of functions...