Slice conversion between primitive types

sliceconv

GoDoc Build Status Coverage Status Go Report Card

Sliceconv implements conversions to and from string representations of primitive types on entire slices. The package supports types int, float64, bool, and string. This package takes its cue from the Golang standard library's strconv.

Installation

If you do not have Go installed yet, you can find installation instructions here.

To pull the most recent version of sliceconv, use go get.

go get -u github.com/Henry-Sarabia/sliceconv

Then import the package into your project.

import "github.com/Henry-Sarabia/sliceconv"

Usage

Strings to Integers

As an example, assume you have a list of test scores as a slice of strings. You mean to find the highest score by passing the list into a findMax function. Unfortunately, the function has the signature findMax([]int) int. Using sliceconv, simply convert the slice of strings into a slice of ints to resolve the issue.

scores := []string{"98", "85", "100", "76", "92"}

ints, err := sliceconv.Atoi(scores)
if err != nil {
	// handle error
}

max := findMax(ints)
// output: 100

Be aware that the sliceconv.Atoi function fulfills the same contract as its counterpart strconv.Atoi. That is to say, the Atoi functions treat the strings as integers in base 10 and will return an error if any of the resulting integers cannot fit into the regular int type.

Integers to Strings

This time around, assume you still have a list of test scores but as a slice of ints. You mean to format a class report card by passing the list of scores into a formatReport function. With a streak of bad luck, the function has the signature formatReport([]string) string. With sliceconv, you can just convert the slice of ints into a slice of strings to satisfy the requirements.

scores := []int{98, 85, 100, 76, 92}

str := sliceconv.Itoa(scores)
report := formatReport(str)
// output: student_1: 98, student_2: 85, ..., student_5: 92

Similarly to sliceconv.Atoi, the sliceconv.Itoa function assumes the integers are in base 10.

Strings to Floats

Sticking to the test score example, assume you have a list of test scores as a slice of strings. You mean to find the average score by passing the list into an averaging function with the signature findAvg([]float64) float64. Taking advantage of sliceconv, you can convert the entire list of strings into a slice of floats.

scores := []string{"98.5", "85.1", "100", "76.9", "92.3"}

flts, err := sliceconv.Atof(scores)
if err != nil {
	// handle error
}

avg := findAvg(flts)
// output: 90.56

Be aware that the sliceconv.Atof function assumes the stringified floats have a bitsize of 64.

Floats to Strings

Again, assume you have a list of test scores but as a slice of float64s. You mean to format a class report card by passing the list of scores into a formatReport function. The function has the following signature: formatReport([]string) string. Using sliceconv, simply convert the slice of float64s into a slice of strings for the formatReport function.

scores := []float64{98.5, 85.1, 100, 76.9, 92.3}

str := sliceconv.Ftoa(scores)
report := formatReport(str)
// output: student_1: 98.5, student_2: 85.1, ..., student_5: 92.3

Please take note that the sliceconv.Ftoa function will fulfill the following contract: the string representation of the provided floats will have no exponent, the smallest precision needed to properly represent the number, and a bitsize of 64.

Strings to Bools

Let's assume a slightly more contrived example to get things going. Assume you have student's answer to a question asking them to list out the truth table for a logical conjuction. The answer is provided as a two dimensional slice. You have a function checkTable but it expects a 2D slice of bools, not strings. To resolve this, you can simply iterate through the slices and pass them each into one of the sliceconv functions.

str := []string{
	[]string{"T", "T", "T"},
    []string{"T", "F", "F"},
    []string{"F", "T", "F"},
    []string{"F", "F", "F"},
}

var bools []bool
for _, s := range str {
	b, err := sliceconv.Atob(s) // conversion happens here
	if err != nil {
		// handle error
	}
	
	bools = append(bools, b)
}

ok := checkTable(bools)
// output: true

As you can see from the example, the Atob function isn't limited to the straightfoward "true" and "false" strings. In fact, Atob is not case-sensitive and can accept the following: "1", "t", "true", "0", "f", and "false".

Bools to Strings

For this example, suppose you have the response to a true or false survey for a single student. You have the answers in the form of a slice of bools. You mean to display these answers in a report using a function with the signature formatReport([]string) string. Because this function only accepts a slice of strings, you will need to use the sliceconv package to convert your slice of bools.

bools := []bool{true, false, false, true, true}

str := sliceconv.Btoa(bools)
report := formatReport(str)
// output: Q1: true, Q2: false, Q3: false, Q4: true, Q5: true

Contributions

If you would like to contribute to this project, please adhere to the following guidelines.

  • Submit an issue describing the problem.
  • Fork the repo and add your contribution.
  • Add appropriate tests.
  • Run go fmt, go vet, and golint.
  • Prefer idiomatic Go over non-idiomatic code.
  • Follow the basic Go conventions found here.
  • If in doubt, try to match your code to the current codebase.
  • Create a pull request with a description of your changes.

I'll review pull requests as they come in and merge them if everything checks out.

Any and all contributions are greatly appreciated. Thank you!

Owner
Henry Sarabia
I have a BS in CS at CSU Fresno. I am a full stack developer who primarily works in Go and TypeScript with React and Vue to develop web applications and APIs.
Henry Sarabia
Comments
  • Package should have tagged releases

    Package should have tagged releases

    Adopting semantic versioning using git tags will allow users to differentiate versions of the package and, more importantly, identify when the package has made a breaking change.

  • Reflect v1.0.1 in README

    Reflect v1.0.1 in README

    When issue #18 is resolved, the README needs to be updated to reflect the changes. One of the examples lists the current accepted boolean string representations.

  • Change Atob to be case-insensitive

    Change Atob to be case-insensitive

    As of v1.0.0, only "true", "True", and "TRUE" are valid string representations of boolean value true. This is the same for the false boolean value. There is no reason to not accept any combination of upper and lowercase characters.

  • README should reflect bool support

    README should reflect bool support

    As of now, the README only describes the usage of the package between integers, floats, and strings. It should be updated to reflect the newly added support for bools and strings as well.

  • README should reflect float support

    README should reflect float support

    As of now, the README only describes the usage of the package between integers and strings. It should be updated to reflect the newly added support for floats and strings as well.

  • Atoi tests are missing error cases

    Atoi tests are missing error cases

    The table driven tests for the Atoi function are missing the error cases; cases where one or more of the provided strings are not integers. These cases should be added for full test coverage.

  • Package is missing a README

    Package is missing a README

    There is no README for this package yet. Add a README file with information on what the package is used for, how to use it and how to contribute. Also add build status, test coverage, and Go report card score.

  • Package is missing Travis CI and Coveralls integration

    Package is missing Travis CI and Coveralls integration

    This package is not integrated with Travis CI and Coveralls yet so its build and test coverage are unknown to other GitHub users. Add a .travis.yml file and activate coverage.

  • Variadic parameters are unwieldly in this context

    Variadic parameters are unwieldly in this context

    Although variadic parameters seemed like a good idea at the time of creating the package, they actually lead to extra boilerplate when calling the package functions. The sliceconv package is meant for converting slices of primitive types to another slice of a primitive type; the use-case of converting a single variable is already covered under the regular strconv package and is out of scope for this package.

    Package functions should simply take a slice of primitive types.

efaceconv - Code generation tool for high performance conversion from interface{} to immutable type without allocations.

efaceconv High performance conversion from interface{} to immutable types without additional allocations This is tool for go generate and common lib (

May 14, 2022
COCO (Color Converter) is a color conversion library for Go.

COCO (Color Converter) for Go COCO (Color Converter) is a color conversion library for Go. Heavily inspired by NPM's color-convert. It converts all wa

Oct 4, 2022
A color manipulation and conversion library for Go. 🌈 ✨

Khroma Khroma is a color manipulation and conversion library for Go. ✨ ?? Example package main import ( "log" "github.com/qbee-org/khroma" ) func

May 30, 2022
💪 Helper Utils For The Go: string, array/slice, map, format, cli, env, filesystem, test and more.
💪 Helper Utils For The Go: string, array/slice, map, format, cli, env, filesystem, test and more.

?? Helper Utils For The Go: string, array/slice, map, format, cli, env, filesystem, test and more. Go 的一些工具函数,格式化,特殊处理,常用信息获取等等

Jan 6, 2023
make slice items unique in go

make slice items unique in go

Jan 20, 2022
Tiny Go tool for running multiple functions concurrently and collecting their results into an error slice.

Overview Short for "ConCurrent". Tiny Go tool for running multiple functions concurrently and collecting their results into an error slice. Dependency

Nov 22, 2021
Wrap byte read options with uniform interface for io.Reader and byte slice

nibbler Nibble chunks from Reader streams and slice in a common way Overview This is a golang module that provides an interface for treating a Reader

Dec 23, 2021
Go 1.18 generics based slice and sorts.

genfuncs import "github.com/nwillc/genfuncs" Package genfuncs implements various functions utilizing Go's Generics to help avoid writing boilerplate c

Jan 2, 2023
Slice - provides generic Map, Reduce and Filter functions for Go.

slice slice is a simple Go package to provide generic versions of Map, Reduce and Filter on slices. I mainly wrote it as an exercise to get more famil

Jan 1, 2023
🍕 Enjoy a slice! A utility library for dealing with slices and maps that focuses on type safety and performance.

?? github.com/elliotchance/pie Enjoy a slice! pie is a library of utility functions for common operations on slices and maps. Quick Start FAQ What are

Dec 30, 2022
Govalid is a data validation library that can validate most data types supported by golang

Govalid is a data validation library that can validate most data types supported by golang. Custom validators can be used where the supplied ones are not enough.

Apr 22, 2022
Golang code-generators used to implement Kubernetes-style API types.

code-generator Golang code-generators used to implement Kubernetes-style API types. Purpose These code-generators can be used in the context of Custom

Dec 30, 2022
Some utility functions for generic types in Go.

GOUF - Utility Functions for generic types Go team released Go 1.18 beta recently with support for Generics(a.k.a type parameters). This package provi

Apr 13, 2022
checkspaces is a checker for spaces between // and directives.

checkspaces checks if there is a space between // and directives.

Dec 10, 2021
CSPFinder is a tool to compare ROI of selling Cash Secure Put options between different tickers for different expiry dates.

CSPFinder is a tool to compare ROI of selling Cash Secure Put options between different tickers for different expiry dates. It is intended to help open new cash secured put positions.

Dec 21, 2021
Go package to nicely calculate distance between coordinates using the Haversine formula.

go-haversine Heavily inspired by Umahmood's haversine, go-haversine provides a nice Go interface to calculate distance between coordinates using the h

Apr 2, 2022
Null Types, Safe primitive type conversion and fetching value from complex structures.

Typ Typ is a library providing a powerful interface to impressive user experience with conversion and fetching data from built-in types in Golang Feat

Sep 26, 2022
MySQL Storage engine conversion,Support mutual conversion between MyISAM and InnoDB engines.

econvert MySQL Storage engine conversion 简介 此工具用于MySQL存储引擎转换,支持CTAS和ALTER两种模式,目前只支持MyISAM和InnoDB存储引擎相互转换,其它引擎尚不支持。 注意:当对表进行引擎转换时,建议业务停止访问或者极少量访问时进行。 原

Oct 25, 2021
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

Dec 28, 2021
Scan database/sql rows directly to structs, slices, and primitive types

Scan Scan standard lib database rows directly to structs or slices. For the most comprehensive and up-to-date docs see the godoc Examples Multiple Row

Dec 28, 2022