Functions in Carbon Language

functions in carbon language
Table of Contents Hide
  1. Introduction
  2. Code Example –
  3. Conclusion

Functions in carbon language has the same role as in C, Php or any other functional language. It is used to separate a functionality for reuse. For example, a function to add two numbers.


The carbon function structure is like this –

fn function_name (parameters) -> return_type {}


  • fn – Indicates that the entity is a function.
  • function_name – Name of your function.
  • parameters – Comma separated list of parameters along with their types.
  • return_type – Data type of the value which the function will return. Skip it if function is not returning anything.

Code Example –

fn multiply (x: i32, y: i32) -> i64 {
    return x * y;

Here we created a function to multiply two 32 bit integers which will result in a 64 bit integer. So, the return type is i64.

Let’s see another example –

package Sorting api;

fn Partition[T:! Comparable & Movable](s: Slice(T)) -> i64 {
  var i: i64 = -1;

  for (e: T in s) {
    if (e <= s.Last()) {
      Swap(&s[i], &e);
  return i;

fn QuickSort[T:! Comparable & Movable](s: Slice(T)) {
  if (s.Size() <= 1) {
  let p: i64 = Partition(s);
  QuickSort(s[:p - 1]);
  QuickSort(s[p + 1:]);

This example is an implementation of QuickSort algorithm. Code credit goes to Carbon team.


Functions in Carbon is an essential tool for modularizing the code for reuse and refactoring. The basic functionality is similar to the functions provided by any functional language.

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like
operators in carbon language

Operators in Carbon Language

Table of Contents Hide ArithmeticBitwise & BitshiftComparisonConversionLogicalIndexingFunction CallPointerMoveConclusion We have a number of operators in Carbon language like – Arithmetic, Bitwise, BitShift, Comparison, Conversion, Logical, Indexing, function call, pointer, move…
View Post
pointers in carbon language

Pointers in Carbon Language

Pointers in Carbon language are similar to C++. The type of pointers-to-values-of-type-P is written as P*. Carbon pointers do not support pointer arithmetic. What operations are supported by Pointers in…
View Post
introduction to carbon language - what and why it is created

Introduction to Carbon Language

Table of Contents Hide IntroductionFeatures of Carbon LanguageWhy developed Carbon? Why not upgraded C++?Where Carbon could be used?Carbon is written in which language?Code Example Carbon Language is the successor to…
View Post