Go library that makes it easy to work with physical types, e.g. distances, velocities and angles.

Overview

Build Status GoDoc

Units

Use at your own risk

Note that this library is NOT production ready. If you want to use it anyway, contributions and bug reports are welcome!

Breaking changes!

This branch of the units library is introduces breaking changes to the API. To use the old API, please checkout tag v0.0.1. If you download the units library via go get, consider using a tool such as Glide instead to help you install/vendor specific versions of your Go dependencies.

To instead use the new API, see this short migration guide for more information.

TODO

  • Code generation for sub-packages
  • Sub-package for angle, angular velocity and acceleration
  • Sub-package for linear distance, velocity and acceleration
  • Sub-package for planar coordinates based on distance and angle
  • Support for volume, volumetric flow rate (velocity) and acceleration
  • Support for mass, mass flow rate (velocity) and acceleration
  • Support for force, work and torque
  • Metric units
  • Modern Imperial units
  • Appropriate test coverage per package.

About

Units is a small Go package that utilizes Go's strict type system to achieve better type safety when storing and doing simple mathematical operations on physical units. The concept is very similar to that of the time.Duration type in the Go standard library.

It currently has the following sub-packages:

  • angular defines the types:
    • Angle
    • Velocity
    • Acceleration
  • linear define the types:
    • Distance
    • Velocity
    • Acceleration
  • planar defines the types:
    • Point
    • Area

Each type has defined constants for relevant units. In general, you don't need to worry about which unit the underlying values is stored as, as long as you always multiply with a relevant uint when you first set your value. E.g.:

var a angular.Angle = 90 * angular.Degrees

Why would I want to use the units package?

The Mars Climate Orbiter crashed into Mars when software producing the non-SI units of pound-seconds was used to generate input to a program expecting newton-seconds (N s). While the units package would not have prevented that particular issue of communication between programs, the goal is that it will help you to avoid unit related mistakes within your own program, and to make working with various units as straight-forward and painless as possible.

Our experience

We found an earlier version of this code surprisingly useful back in 2012, when we where developing an autonomous robot using Go for the high-level programming.

While we still used float64 values in the matrices that calculated the next system states, we found using the units package for the input and output values of various blocks extremely useful. This package helped us verify that we never did something stupid like passing a distance to a function that wanted the velocity. The simplicity of using the return value from .Normalize()on an angle, also made it very easy for us to ensure normalized angles for our navigation system.

Of course, we used metric values for both internal and displaying purposes, but the aim is also that this package will help those who wish to provide non-metric units as input or display values for their programs.

Simple example

This example shows that you can divide linear.Distance with a time.Duration (standard library) to get a velocity, as well as use arbitrary units for input and display purposes.

package main

import(
	"fmt"
	"time"
	"github.com/smyrman/units/linear"
)

func main() {
	d := 66 * linear.Feet
	t := 2 * time.Second
	v := d.DivDuration(t)
	fmt.Printf("v = %.2f m/s\n", v.MetersPerSecond())
	fmt.Printf("v = %.2f kmph\n", v.KilometersPerHour())
	fmt.Printf("v = %.2f mph\n", v.MilesPerHour())
}

See the godoc reference docs for a full list of methods per type.

Origin

The units package was originally developed for use in the robot Loke (eng:Loki), that participated in the Eurobot competition in France in 2012.

Migrating from v0.0.1

Since v0.0.1, the package layout has been completely changed. Type and constant definitions have been moved into sub-packages to allow for shorter names, and a more restricted scope from which package symmetry can arise.

To migrate, search and replace the following:

  • units.Distance -> linear.Distance
  • units.Velocity -> linear.Velocity
  • units.Angle -> angular.Angle
  • units.AngularVelocity -> angular.Velocity
  • units.Coordinate -> planar.Point

Then, assure the proper imports, most conveniently through the use of goimports, or manually by replacing the "github.com/smyrman/units" import with the appropriate import(s):

  • "github.com/smyrman/units/linear"
  • "github.com/smyrman/units/angular"
  • "github.com/smyrman/units/planar"
You might also like...
Library to work with MimeHeaders and another mime types. Library support wildcards and parameters.

Mime header Motivation This library created to help people to parse media type data, like headers, and store and match it. The main features of the li

Library providing opanapi3 and Go types for store/validation and transfer of ISO-4217, ISO-3166, and other types.

go-types This library has been created with the purpose to facilitate the store, validation, and transfer of Go ISO-3166/ISO-4217/timezones/emails/URL

A quick and easy password protected web server for your files. httpfolder makes downloading/uploading files from your current working directory easy, even for fairly large files.

httpfolder A quick and easy password protected web server for your files. httpfolder makes downloading/uploading files from your current working direc

Optional is a library that provides option types for Go types.

Option Optional is a library that provides option types for Go types. Installation Golang version 1.18 + required go get -u github.com/eatmoreapple/op

Go linter that checks types that are json encoded - reports unsupported types and unnecessary error checks

Checks types passed to the json encoding functions. Reports unsupported types and reports occations, where the check for the returned error can be omited.

Plugin which makes tmux work and feel like i3wm

Tmux Tilish This is a plugin that makes tmux behave more like a typical dynamic window manager. It is heavily inspired by i3wm, and most keybindings a

LTF is a minimal, transparent Terraform wrapper. It makes Terraform projects easier to work with.

LTF Status: alpha LTF is a minimal, transparent Terraform wrapper. It makes Terraform projects easier to work with. In standard Terraform projects, th

Genv is a library for Go (golang) that makes it easy to read and use environment variables in your projects. It also allows environment variables to be loaded from the .env file.

genv Genv is a library for Go (golang) that makes it easy to read and use environment variables in your projects. It also allows environment variables

Minutes is a CLI tool for synchronizing work logs between multiple time trackers, invoicing, and bookkeeping software to make entrepreneurs' daily work easier.
Minutes is a CLI tool for synchronizing work logs between multiple time trackers, invoicing, and bookkeeping software to make entrepreneurs' daily work easier.

Minutes is a CLI tool for synchronizing work logs between multiple time trackers, invoicing, and bookkeeping software to make entrepreneurs' daily work easier.

golang long polling library.  Makes web pub-sub easy via HTTP long-poll server :smiley: :coffee: :computer:
golang long polling library. Makes web pub-sub easy via HTTP long-poll server :smiley: :coffee: :computer:

golongpoll Golang long polling library. Makes web pub-sub easy via an HTTP long-poll server. New in v1.1 Deprecated CreateManager and CreateCustomMana

The DGL Operator makes it easy to run Deep Graph Library (DGL) graph neural network training on Kubernetes

DGL Operator The DGL Operator makes it easy to run Deep Graph Library (DGL) graph neural network distributed or non-distributed training on Kubernetes

Go library that makes it easy to add automatic retries to your projects, including support for context.Context.

go-retry Go library that makes it easy to add automatic retries to your projects, including support for context.Context. Example with context.Context

GoBinClassify - A library that makes it easy to classify into groups

GoBinClassify GoBinClassify is a library that makes it easy to classify into gro

lambda-go-api-proxy makes it easy to port APIs written with Go frameworks such as Gin to AWS Lambda and Amazon API Gateway.

aws-lambda-go-api-proxy makes it easy to run Golang APIs written with frameworks such as Gin with AWS Lambda and Amazon API Gateway.

The OCI Service Operator for Kubernetes (OSOK) makes it easy to connect and manage OCI services from a cloud native application running in a Kubernetes environment.

OCI Service Operator for Kubernetes Introduction The OCI Service Operator for Kubernetes (OSOK) makes it easy to create, manage, and connect to Oracle

Cloudprober is a monitoring software that makes it super-easy to monitor availability and performance of various components of your system.

Cloudprober is a monitoring software that makes it super-easy to monitor availability and performance of various components of your system. Cloudprobe

ghcv-cli makes it easy to view the user-created issues, pull requests, and repositories in the terminal.
ghcv-cli makes it easy to view the user-created issues, pull requests, and repositories in the terminal.

ghcv-cli ghcv-cli makes it easy to view the user-created issues, pull requests, and repositories in the terminal. About Show a list of pull requests c

go.rice is a Go package that makes working with resources such as html,js,css,images,templates, etc very easy.

go.rice go.rice is a Go package that makes working with resources such as html,js,css,images and templates easy. During development go.rice will load

Rem is a CLI trash which makes it ridiculously easy to recover files.
Rem is a CLI trash which makes it ridiculously easy to recover files.

Rem is a CLI trash which makes it ridiculously easy to recover files. We've all had that moment when we've deleted something we realised we shouldn't have. It sucks. Let's fix that!

Comments
  • Auto-generate code

    Auto-generate code

    Auto-generate most of the code. Split into sub-packages to get better grouping and symmetry of various units. This will break backwards-compatibility.

    opened by smyrman 2
  • update to use go.mod and GitHubActions

    update to use go.mod and GitHubActions

    Update the code to use go.mod (dependencies) and GitHub actions (CI). Set the go version to go 1.17 and use the embed feature for code generation.

    Go through the code and correct linter issues.

    opened by smyrman 0
  • waffle.io Badge

    waffle.io Badge

    Merge this to receive a badge indicating the number of issues in the ready column on your waffle.io board at https://waffle.io/smyrman/units

    This was requested by a real person (user smyrman) on waffle.io, we're not trying to spam you.

    opened by waffle-iron 0
  • Imporove test coverage

    Imporove test coverage

    We should improve the test coverage of the various packages. With more reasoning below, the following should have tests:

    • All code that is not generated should have full test coverage.
    • The list of constants from the generate.json files should be tested.
    • Each "class" of generated functions should have (at least) one test (per type).

    With code generation, the risk of human blunders have reduced significantly. Most of the code is generated by for-loops, that only varies which constant to use E.g. Meters(), Centimeters(), Feet() etc. for the linear.Distance type. Rather than having a percentage goal for how high the test coverage should be, it makes more sense to have a goal on what to test. For the auto-generated code, it should be enough to test one of the functions generated per for-loop, as well as ensuring that the constant list itself does not contain any errors. For what little code is not generated, full test coverage should not be to much work.

    [zube]: Ready 
    opened by smyrman 1
Releases(v0.2.0)
  • v0.2.0(Dec 2, 2022)

    What's Changed

    • update to use go.mod and GitHubActions by @smyrman in https://github.com/smyrman/units/pull/4

    Full Changelog: https://github.com/smyrman/units/compare/v0.1.0...v0.2.0

    Source code(tar.gz)
    Source code(zip)
  • v0.1.0(Dec 15, 2016)

    This release marks the transition to a new package hierarchy based on code generation.

    Since v0.0.1, the package layout has been completely changed. Type and constant definitions have been moved into sub-packages to allow for shorter names, and a more restricted scope from which package symmetry can arise.

    To migrate, search and replace the following:

    • units.Distance -> linear.Distance
    • units.Velocity -> linear.Velocity
    • units.Angle -> angular.Angle
    • units.AngularVelocity -> angular.Velocity
    • units.Coordinate -> planar.Point

    Then, assure the proper imports, most conveniently through the use of goimports, or manually by replacing the "github.com/smyrman/units" import with the appropriate import(s):

    • "github.com/smyrman/units/linear"
    • "github.com/smyrman/units/angular"
    • "github.com/smyrman/units/planar"
    Source code(tar.gz)
    Source code(zip)
  • v0.0.1(Aug 26, 2016)

Owner
Sindre Røkenes Myren
Sindre Røkenes Myren
A well tested and comprehensive Golang statistics library package with no dependencies.

Stats - Golang Statistics Package A well tested and comprehensive Golang statistics library / package / module with no dependencies. If you have any s

Montana Flynn 2.6k Dec 27, 2022
Go language bindings for the COIN-OR Linear Programming library

clp Description The clp package provides a Go interface to the COIN-OR Linear Programming (CLP) library, part of the COIN-OR (COmputational INfrastruc

Los Alamos National Laboratory 38 Nov 9, 2022
GNU GSL Statistics library (v1.15, GPLv3) implemented in Go

Statistics Pure Go implementation of the GSL Statistics library. For the API overview see Godoc. Why create this repository when there is also "github

grd 77 Nov 23, 2021
Go Library [DEPRECATED]

Tideland Go Library Description The Tideland Go Library contains a larger set of useful Google Go packages for different purposes. ATTENTION: The cell

Tideland 194 Nov 15, 2022
high performance fixed decimal place math library for Go

Summary A fixed place numeric library designed for performance. All numbers have a fixed 7 decimal places, and the maximum permitted value is +- 99999

robert engels 295 Dec 6, 2022
This is a go implementation of Segmented Sieve and non Segmented sieve to produce prime numbers concurrently.

Prime This is a Go library to produce prime numbers using all available cpu cores. Installation $ go get github.com/kavehmz/prime Usage package main

Kaveh Mousavi Zamani 25 Dec 30, 2022
Sparse matrix formats for linear algebra supporting scientific and machine learning applications

Sparse matrix formats Implementations of selected sparse matrix formats for linear algebra supporting scientific and machine learning applications. Co

James Bowman 135 Dec 12, 2022
Geographic coordinates and distances library written in Go.

Geographic coordinates and distances library written in Go.

Conner Douglass 2 Apr 5, 2022
Plugs module to see different types of plug types needed in different countries, and a comparison tool between two countries plug socket types.

plugs Importing the module: go get github.com/matthewboyd/plugs "github.com/matthewboyd/plugs" How to use the module: There are two functions wi

Matthew Boyd 2 Dec 28, 2021
QR secrets is a cryptographically secure mechanism to store secret data with the highest levels of security and store it on physical paper.

QR Secrets QR secrets is a cryptographically secure mechanism to store secret data with the highest levels of security. Incorporating; AES256-GCM-HKDF

Go Compile 0 Jan 12, 2022