{"id":8561,"date":"2024-09-19T04:51:51","date_gmt":"2024-09-19T04:51:51","guid":{"rendered":"https:\/\/metaschool.so\/articles\/?p=8561"},"modified":"2025-01-16T08:07:26","modified_gmt":"2025-01-16T08:07:26","slug":"golang-string-to-integer","status":"publish","type":"post","link":"https:\/\/metaschool.so\/articles\/golang-string-to-integer\/","title":{"rendered":"How to Convert String to Integer in Go? Golang String to Int Guide"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_56_1 ez-toc-wrap-left counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title \" >Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/metaschool.so\/articles\/golang-string-to-integer\/#Converting_String_to_Integer\" title=\"Converting String to Integer \">Converting String to Integer <\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/metaschool.so\/articles\/golang-string-to-integer\/#Use_Cases\" title=\"Use Cases\">Use Cases<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/metaschool.so\/articles\/golang-string-to-integer\/#Conclusion\" title=\"Conclusion\">Conclusion<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/metaschool.so\/articles\/golang-string-to-integer\/#FAQs\" title=\"FAQs\">FAQs<\/a><\/li><\/ul><\/nav><\/div>\n\n<p>In Go (Golang), converting a string to an integer is a common task, especially when working with user inputs or data from external sources. Go provides built-in functions to facilitate this conversion, making it straightforward. In this guide, we&#8217;ll explore how to convert strings to integers using the <code>strconv<\/code> package, which is part of Go&#8217;s standard library.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Converting_String_to_Integer\"><\/span>Converting String to Integer <span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Let&#8217;s explore some methods that we can use to convert data from string to integer type in Go.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Method 0: Implementation from Scratch<\/h3>\n\n\n\n<p>Before using built-in functions to convert strings to integers in Go, it&#8217;s important to try the operation yourself. It will increase your understanding of the conversion process and enhance your overall programming skills and concepts in Go.<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#272822\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"package main\n\nimport (\n\t&quot;errors&quot;\n\t&quot;fmt&quot;\n)\n\nfunc stringToInt(s string) (int, error) {\n\tif s == &quot;&quot; {\n\t\treturn 0, errors.New(&quot;empty string&quot;)\n\t}\n\n\tresult := 0\n\tsign := 1\n\tstartIndex := 0\n\n\t\/\/ Check for a negative sign\n\tif s[0] == '-' {\n\t\tsign = -1\n\t\tstartIndex = 1\n\t} else if s[0] == '+' {\n\t\tstartIndex = 1\n\t}\n\n\t\/\/ Convert each character to its integer value\n\tfor i := startIndex; i &lt; len(s); i++ {\n\t\tdigit := int(s[i] - '0') \/\/ Convert char to int\n\n\t\t\/\/ Check for valid digit\n\t\tif digit &lt; 0 || digit &gt; 9 {\n\t\t\treturn 0, errors.New(&quot;invalid character in string&quot;)\n\t\t}\n\n\t\tresult = result*10 + digit\n\t}\n\n\treturn result * sign, nil\n}\" style=\"color:#F8F8F2;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki monokai\" style=\"background-color: #272822\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #F92672\">package<\/span><span style=\"color: #F8F8F2\"> main<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #F92672\">import<\/span><span style=\"color: #F8F8F2\"> (<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">\t<\/span><span style=\"color: #E6DB74\">&quot;errors&quot;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">\t<\/span><span style=\"color: #E6DB74\">&quot;fmt&quot;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #F92672\">func<\/span><span style=\"color: #F8F8F2\"> <\/span><span style=\"color: #A6E22E\">stringToInt<\/span><span style=\"color: #F8F8F2\">(s <\/span><span style=\"color: #66D9EF; font-style: italic\">string<\/span><span style=\"color: #F8F8F2\">) (<\/span><span style=\"color: #66D9EF; font-style: italic\">int<\/span><span style=\"color: #F8F8F2\">, <\/span><span style=\"color: #66D9EF; font-style: italic\">error<\/span><span style=\"color: #F8F8F2\">) {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">\t<\/span><span style=\"color: #F92672\">if<\/span><span style=\"color: #F8F8F2\"> s <\/span><span style=\"color: #F92672\">==<\/span><span style=\"color: #F8F8F2\"> <\/span><span style=\"color: #E6DB74\">&quot;&quot;<\/span><span style=\"color: #F8F8F2\"> {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">\t\t<\/span><span style=\"color: #F92672\">return<\/span><span style=\"color: #F8F8F2\"> <\/span><span style=\"color: #AE81FF\">0<\/span><span style=\"color: #F8F8F2\">, errors.<\/span><span style=\"color: #66D9EF\">New<\/span><span style=\"color: #F8F8F2\">(<\/span><span style=\"color: #E6DB74\">&quot;empty string&quot;<\/span><span style=\"color: #F8F8F2\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">\t}<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">\tresult <\/span><span style=\"color: #F92672\">:=<\/span><span style=\"color: #F8F8F2\"> <\/span><span style=\"color: #AE81FF\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">\tsign <\/span><span style=\"color: #F92672\">:=<\/span><span style=\"color: #F8F8F2\"> <\/span><span style=\"color: #AE81FF\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">\tstartIndex <\/span><span style=\"color: #F92672\">:=<\/span><span style=\"color: #F8F8F2\"> <\/span><span style=\"color: #AE81FF\">0<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">\t<\/span><span style=\"color: #88846F\">\/\/ Check for a negative sign<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">\t<\/span><span style=\"color: #F92672\">if<\/span><span style=\"color: #F8F8F2\"> s[<\/span><span style=\"color: #AE81FF\">0<\/span><span style=\"color: #F8F8F2\">] <\/span><span style=\"color: #F92672\">==<\/span><span style=\"color: #F8F8F2\"> <\/span><span style=\"color: #E6DB74\">&#39;<\/span><span style=\"color: #AE81FF\">-<\/span><span style=\"color: #E6DB74\">&#39;<\/span><span style=\"color: #F8F8F2\"> {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">\t\tsign <\/span><span style=\"color: #F92672\">=<\/span><span style=\"color: #F8F8F2\"> <\/span><span style=\"color: #F92672\">-<\/span><span style=\"color: #AE81FF\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">\t\tstartIndex <\/span><span style=\"color: #F92672\">=<\/span><span style=\"color: #F8F8F2\"> <\/span><span style=\"color: #AE81FF\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">\t} <\/span><span style=\"color: #F92672\">else<\/span><span style=\"color: #F8F8F2\"> <\/span><span style=\"color: #F92672\">if<\/span><span style=\"color: #F8F8F2\"> s[<\/span><span style=\"color: #AE81FF\">0<\/span><span style=\"color: #F8F8F2\">] <\/span><span style=\"color: #F92672\">==<\/span><span style=\"color: #F8F8F2\"> <\/span><span style=\"color: #E6DB74\">&#39;<\/span><span style=\"color: #AE81FF\">+<\/span><span style=\"color: #E6DB74\">&#39;<\/span><span style=\"color: #F8F8F2\"> {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">\t\tstartIndex <\/span><span style=\"color: #F92672\">=<\/span><span style=\"color: #F8F8F2\"> <\/span><span style=\"color: #AE81FF\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">\t}<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">\t<\/span><span style=\"color: #88846F\">\/\/ Convert each character to its integer value<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">\t<\/span><span style=\"color: #F92672\">for<\/span><span style=\"color: #F8F8F2\"> i <\/span><span style=\"color: #F92672\">:=<\/span><span style=\"color: #F8F8F2\"> startIndex; i <\/span><span style=\"color: #F92672\">&lt;<\/span><span style=\"color: #F8F8F2\"> <\/span><span style=\"color: #66D9EF\">len<\/span><span style=\"color: #F8F8F2\">(s); i<\/span><span style=\"color: #F92672\">++<\/span><span style=\"color: #F8F8F2\"> {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">\t\tdigit <\/span><span style=\"color: #F92672\">:=<\/span><span style=\"color: #F8F8F2\"> <\/span><span style=\"color: #66D9EF\">int<\/span><span style=\"color: #F8F8F2\">(s[i] <\/span><span style=\"color: #F92672\">-<\/span><span style=\"color: #F8F8F2\"> <\/span><span style=\"color: #E6DB74\">&#39;<\/span><span style=\"color: #AE81FF\">0<\/span><span style=\"color: #E6DB74\">&#39;<\/span><span style=\"color: #F8F8F2\">) <\/span><span style=\"color: #88846F\">\/\/ Convert char to int<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">\t\t<\/span><span style=\"color: #88846F\">\/\/ Check for valid digit<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">\t\t<\/span><span style=\"color: #F92672\">if<\/span><span style=\"color: #F8F8F2\"> digit <\/span><span style=\"color: #F92672\">&lt;<\/span><span style=\"color: #F8F8F2\"> <\/span><span style=\"color: #AE81FF\">0<\/span><span style=\"color: #F8F8F2\"> <\/span><span style=\"color: #F92672\">||<\/span><span style=\"color: #F8F8F2\"> digit <\/span><span style=\"color: #F92672\">&gt;<\/span><span style=\"color: #F8F8F2\"> <\/span><span style=\"color: #AE81FF\">9<\/span><span style=\"color: #F8F8F2\"> {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">\t\t\t<\/span><span style=\"color: #F92672\">return<\/span><span style=\"color: #F8F8F2\"> <\/span><span style=\"color: #AE81FF\">0<\/span><span style=\"color: #F8F8F2\">, errors.<\/span><span style=\"color: #66D9EF\">New<\/span><span style=\"color: #F8F8F2\">(<\/span><span style=\"color: #E6DB74\">&quot;invalid character in string&quot;<\/span><span style=\"color: #F8F8F2\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">\t\t}<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">\t\tresult <\/span><span style=\"color: #F92672\">=<\/span><span style=\"color: #F8F8F2\"> result<\/span><span style=\"color: #F92672\">*<\/span><span style=\"color: #AE81FF\">10<\/span><span style=\"color: #F8F8F2\"> <\/span><span style=\"color: #F92672\">+<\/span><span style=\"color: #F8F8F2\"> digit<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">\t}<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">\t<\/span><span style=\"color: #F92672\">return<\/span><span style=\"color: #F8F8F2\"> result <\/span><span style=\"color: #F92672\">*<\/span><span style=\"color: #F8F8F2\"> sign, <\/span><span style=\"color: #AE81FF\">nil<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">}<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h4 class=\"wp-block-heading\">Explanation<\/h4>\n\n\n\n<p>Let&#8217;s look at a detailed explanation of this code to better understand the process of conversion.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Function Definition<\/strong>: The <code>stringToInt<\/code> function takes a string as input and returns an integer and an error.<\/li>\n\n\n\n<li><strong>Empty String Check<\/strong>: It first checks if the string is empty and returns an error if it is.<\/li>\n\n\n\n<li><strong>Sign Handling<\/strong>: It checks for a negative (<code>-<\/code>) or positive (<code>+<\/code>) sign at the beginning of the string. The sign is stored, and the starting index for conversion is adjusted accordingly.<\/li>\n\n\n\n<li><strong>Character Conversion<\/strong>: The function iterates over each character, and converts it to its integer value by subtracting the ASCII value of <code>'0'<\/code>, and constructs the final integer.<\/li>\n\n\n\n<li><strong>Error Handling<\/strong>: If an invalid character (non-digit) is encountered, it returns an error.<\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading\">Example<\/h4>\n\n\n\n<p>The example demonstrates a dry run of the code.<\/p>\n\n\n\n<p>Suppose you have the string <code>\"123\"<\/code> and you want to convert the character <code>'2'<\/code> to its integer value.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Character to Convert<\/strong>: <code>'2'<\/code><\/li>\n\n\n\n<li><strong>ASCII Value of &#8216;2&#8217;<\/strong>: The ASCII value of the character <code>'2'<\/code> is <code>50<\/code>.<\/li>\n\n\n\n<li><strong>ASCII Value of &#8216;0&#8217;<\/strong>: The ASCII value of the character <code>'0'<\/code> is <code>48<\/code>.<\/li>\n\n\n\n<li><strong>Conversion<\/strong>: <span style=\"background-color: var(--nv-site-bg);color: var(--nv-text-color);font-family: var(--bodyfontfamily);font-size: var(--bodyfontsize);font-weight: var(--bodyfontweight);letter-spacing: var(--bodyletterspacing);text-transform: var(--bodytexttransform)\">To get the integer value of the character <\/span><code style=\"color: var(--nv-text-color);font-size: var(--bodyfontsize);font-weight: var(--bodyfontweight);letter-spacing: var(--bodyletterspacing);text-transform: var(--bodytexttransform)\">'2'<\/code><span style=\"background-color: var(--nv-site-bg);color: var(--nv-text-color);font-family: var(--bodyfontfamily);font-size: var(--bodyfontsize);font-weight: var(--bodyfontweight);letter-spacing: var(--bodyletterspacing);text-transform: var(--bodytexttransform)\">, you subtract the ASCII value of <\/span><code style=\"color: var(--nv-text-color);font-size: var(--bodyfontsize);font-weight: var(--bodyfontweight);letter-spacing: var(--bodyletterspacing);text-transform: var(--bodytexttransform)\">'0'<\/code><span style=\"background-color: var(--nv-site-bg);color: var(--nv-text-color);font-family: var(--bodyfontfamily);font-size: var(--bodyfontsize);font-weight: var(--bodyfontweight);letter-spacing: var(--bodyletterspacing);text-transform: var(--bodytexttransform)\"> from the ASCII value of <\/span><code style=\"color: var(--nv-text-color);font-size: var(--bodyfontsize);font-weight: var(--bodyfontweight);letter-spacing: var(--bodyletterspacing);text-transform: var(--bodytexttransform)\">'2'<\/code>. <em>Integer&nbsp;Value = ASCII(<code>\u20322\u2032<\/code>) \u2212 ASCII(<code>\u20320\u2032<\/code>) = 50 \u2212 48 = 2<\/em> <\/li>\n<\/ol>\n\n\n\n<p>This process effectively translates the character representation of a digit to its corresponding integer value. You can apply this same method to each character in the string to construct the full integer. For example, when iterating over the string <code>\"123\"<\/code>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>For <code>'1'<\/code>: 49 \u2212 48 = 1<\/li>\n\n\n\n<li>For <code>'2'<\/code>: 50 \u2212 48 = 2<\/li>\n\n\n\n<li>For <code>'3'<\/code>: 51 \u2212 48 = 3<\/li>\n<\/ul>\n\n\n\n<p>Finally, these values are combined to form the integer <code>123<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Method 1: Using <code>strconv.Atoi()<\/code><\/h3>\n\n\n\n<p>Go&#8217;s <code>strconv<\/code> package provides functions to convert strings to various numeric types, including integers. We will use the <code>strconv.Atoi()<\/code> function which stands for &#8220;ASCII to integer&#8221; for converting strings to integers.<\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#272822\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"package main\n\nimport (\n    &quot;fmt&quot;\n    &quot;strconv&quot;\n)\n\nfunc main() {\n    str := &quot;12345&quot; \/\/ String to be converted\n    num, err := strconv.Atoi(str) \/\/ Convert string to integer\n\n    if err != nil {\n        fmt.Println(&quot;Error converting string to integer:&quot;, err)\n        return\n    }\n\n    fmt.Println(&quot;The converted integer is:&quot;, num) \/\/ Output: 12345\n}\" style=\"color:#F8F8F2;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki monokai\" style=\"background-color: #272822\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #F92672\">package<\/span><span style=\"color: #F8F8F2\"> main<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #F92672\">import<\/span><span style=\"color: #F8F8F2\"> (<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">    <\/span><span style=\"color: #E6DB74\">&quot;fmt&quot;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">    <\/span><span style=\"color: #E6DB74\">&quot;strconv&quot;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #F92672\">func<\/span><span style=\"color: #F8F8F2\"> <\/span><span style=\"color: #A6E22E\">main<\/span><span style=\"color: #F8F8F2\">() {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">    str <\/span><span style=\"color: #F92672\">:=<\/span><span style=\"color: #F8F8F2\"> <\/span><span style=\"color: #E6DB74\">&quot;12345&quot;<\/span><span style=\"color: #F8F8F2\"> <\/span><span style=\"color: #88846F\">\/\/ String to be converted<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">    num, err <\/span><span style=\"color: #F92672\">:=<\/span><span style=\"color: #F8F8F2\"> strconv.<\/span><span style=\"color: #66D9EF\">Atoi<\/span><span style=\"color: #F8F8F2\">(str) <\/span><span style=\"color: #88846F\">\/\/ Convert string to integer<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">    <\/span><span style=\"color: #F92672\">if<\/span><span style=\"color: #F8F8F2\"> err <\/span><span style=\"color: #F92672\">!=<\/span><span style=\"color: #F8F8F2\"> <\/span><span style=\"color: #AE81FF\">nil<\/span><span style=\"color: #F8F8F2\"> {<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">        fmt.<\/span><span style=\"color: #66D9EF\">Println<\/span><span style=\"color: #F8F8F2\">(<\/span><span style=\"color: #E6DB74\">&quot;Error converting string to integer:&quot;<\/span><span style=\"color: #F8F8F2\">, err)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">        <\/span><span style=\"color: #F92672\">return<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">    }<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">    fmt.<\/span><span style=\"color: #66D9EF\">Println<\/span><span style=\"color: #F8F8F2\">(<\/span><span style=\"color: #E6DB74\">&quot;The converted integer is:&quot;<\/span><span style=\"color: #F8F8F2\">, num) <\/span><span style=\"color: #88846F\">\/\/ Output: 12345<\/span><\/span>\n<span class=\"line\"><span style=\"color: #F8F8F2\">}<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p>When converting strings to integers, it&#8217;s important to handle potential errors. The <code>Atoi()<\/code> function returns an error if the string is not a valid representation of an integer. For example, trying to convert <code>\"abc\"<\/code> would result in an error.<\/p>\n\n\n\n<p>Here&#8217;s how to handle such errors:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>str := \"abc\"\nnum, err := strconv.Atoi(str)\nif err != nil {\n    fmt.Println(\"Error:\", err) \/\/ Output: Error: invalid syntax\n} else {\n    fmt.Println(\"The converted integer is:\", num)\n}<\/code><\/pre>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"900\" height=\"842\" src=\"https:\/\/metaschool.so\/articles\/wp-content\/uploads\/2024\/09\/Screenshot-2024-09-19-094548.png\" alt=\"How to Convert String to Integer in Go? - Atoi()\" class=\"wp-image-8574\" srcset=\"https:\/\/metaschool.so\/articles\/wp-content\/uploads\/2024\/09\/Screenshot-2024-09-19-094548.png 900w, https:\/\/metaschool.so\/articles\/wp-content\/uploads\/2024\/09\/Screenshot-2024-09-19-094548-300x281.png 300w, https:\/\/metaschool.so\/articles\/wp-content\/uploads\/2024\/09\/Screenshot-2024-09-19-094548-150x140.png 150w, https:\/\/metaschool.so\/articles\/wp-content\/uploads\/2024\/09\/Screenshot-2024-09-19-094548-768x719.png 768w\" sizes=\"auto, (max-width: 900px) 100vw, 900px\" \/><\/figure>\n<\/div>\n\n\n<h3 class=\"wp-block-heading\">Method 2: Using <code>strconv.ParseInt()<\/code><\/h3>\n\n\n\n<p>If you need to convert a string representation of an integer in a specific base (e.g., binary, octal, hexadecimal), you can use <code>strconv.ParseInt()<\/code>. This function allows you to specify the base of the input string.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Syntax<\/h4>\n\n\n\n<p>The function call can be made using the following syntax format:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func ParseInt(s string, base int, bitSize int) (i int64, err error)<\/code><\/pre>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>s<\/strong> (string): The string to be converted to an integer.<\/li>\n\n\n\n<li><strong>base<\/strong> (int): The <a href=\"https:\/\/math.libretexts.org\/Courses\/Mount_Royal_University\/Higher_Arithmetic\/7%3A_Numeration_Systems\/7.2%3A_Number_Bases\" target=\"_blank\" rel=\"noopener\">numerical base<\/a> for the conversion. This can be:\n<ul class=\"wp-block-list\">\n<li><code>0<\/code>: Base is inferred from the string (e.g., <code>0x<\/code> for hex, <code>0<\/code> for octal, or decimal).<\/li>\n\n\n\n<li><code>2<\/code> to <code>36<\/code>: Specifies the base directly (e.g., <code>10<\/code> for decimal).<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>bitSize<\/strong> (int): The <a href=\"https:\/\/go.dev\/tour\/basics\/11\" target=\"_blank\" rel=\"noopener\">bit size<\/a> of the resulting integer. It can be:\n<ul class=\"wp-block-list\">\n<li><code>0<\/code>: Uses the default size (usually 0-64 depending on the platform).<\/li>\n\n\n\n<li><code>8<\/code>, <code>16<\/code>, <code>32<\/code>, or <code>64<\/code>: Specifies the exact bit size.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<p>The function returns an <code>int64<\/code> value representing the parsed integer. The error will be <code>nil<\/code> if the conversion was successful otherwise it will contain information about the failure.<\/p>\n\n\n\n<p>We can understand it better by an example. Let&#8217;s convert a hexadecimal string to an integer:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>str := \"1a\"\nnum, err := strconv.ParseInt(str, 16, 0) \/\/ Base 16 for hexadecimal\n\nif err != nil {\n    fmt.Println(\"Error converting hexadecimal to integer:\", err)\n} else {\n    fmt.Println(\"The converted integer is:\", num) \/\/ Output: 26<\/code><\/pre>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"949\" height=\"743\" src=\"https:\/\/metaschool.so\/articles\/wp-content\/uploads\/2024\/09\/Screenshot-2024-09-19-094839-1.png\" alt=\"How to Convert String to Integer in Go? - ParseInt()\" class=\"wp-image-8576\" srcset=\"https:\/\/metaschool.so\/articles\/wp-content\/uploads\/2024\/09\/Screenshot-2024-09-19-094839-1.png 949w, https:\/\/metaschool.so\/articles\/wp-content\/uploads\/2024\/09\/Screenshot-2024-09-19-094839-1-300x235.png 300w, https:\/\/metaschool.so\/articles\/wp-content\/uploads\/2024\/09\/Screenshot-2024-09-19-094839-1-150x117.png 150w, https:\/\/metaschool.so\/articles\/wp-content\/uploads\/2024\/09\/Screenshot-2024-09-19-094839-1-768x601.png 768w\" sizes=\"auto, (max-width: 949px) 100vw, 949px\" \/><\/figure>\n<\/div>\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Use_Cases\"><\/span>Use Cases<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>User Input<\/strong>: When reading user input, data is typically received as strings. If you need to perform numerical calculations, you&#8217;ll need to convert these strings to integers.<\/li>\n\n\n\n<li><strong>Data Processing<\/strong>: When working with data from files, APIs, or databases, numeric values may be represented as strings. Converting them allows you to manipulate them mathematically.<\/li>\n\n\n\n<li><strong>Type Safety<\/strong>: Go is a statically typed language, meaning types are enforced at compile time. This enforcement reduces the likelihood of runtime errors, such as attempting arithmetic operations on incompatible types. As a type-safe language, Go can catch type-related errors at compile time, allowing developers to identify issues early in the development process.<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In Go, converting string to integer is a common task that can be done using a couple of methods. We discussed implementing the conversion from scratch and utilizing two built-in functions in the <code>strconv<\/code> package: <code>Atoi()<\/code>, and <code>ParseInt()<\/code>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Implementing from scratch<\/strong> allows for a deeper understanding of string-to-integer conversion. The code we discussed handles empty strings and invalid characters with error checks.<\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Using <code>strconv.Atoi()<\/code><\/strong> converts a string to an integer by automatically inferring base 10. It includes error handling for invalid inputs.<\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Using <code>strconv.ParseInt()<\/code><\/strong> supports conversion from a string in a specified base (e.g., binary, octal, hexadecimal). It allows the specification of bit size for the resulting integer and returns an <code>int64<\/code> value. It also includes error handling for invalid inputs.<\/li>\n<\/ul>\n\n\n\n<p>In addition to mastering string to integer conversion, it&#8217;s worth noting that Go is a vital language in blockchain development. Check out our article <strong><em><a href=\"https:\/\/metaschool.so\/articles\/blockchain-programming-languages-development\/#5_GoLang\">What programming languages are used for blockchain development?<\/a><\/em><\/strong> to learn more about its significance and capabilities in this evolving field.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"FAQs\"><\/span>FAQs<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n<div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-question-1726719565775\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">How does <code>strconv.ParseInt()<\/code> differ from <code>strconv.Atoi()<\/code>?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p><code>strconv.ParseInt()<\/code> allows you to specify the base (from 2 to 36) and bit size for the converted value, making it suitable for various numerical systems, whereas <code>strconv.Atoi()<\/code> is simpler and specifically for base 10.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1726719619560\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">Can I convert negative numbers using these methods?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Yes, both <code>strconv.Atoi()<\/code> and <code>strconv.ParseInt()<\/code> support negative numbers if the string begins with a &#8216;-&#8216; sign. Custom implementations also need to handle this explicitly.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1726719643242\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">What happens if I pass an empty string to these conversion functions?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Passing an empty string will result in an error. In <code>strconv.Atoi()<\/code> and <code>strconv.ParseInt()<\/code>, the error message will indicate that the input is invalid.<\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":19,"featured_media":10981,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"neve_meta_sidebar":"","neve_meta_container":"","neve_meta_enable_content_width":"","neve_meta_content_width":0,"neve_meta_title_alignment":"","neve_meta_author_avatar":"","neve_post_elements_order":"","neve_meta_disable_header":"","neve_meta_disable_footer":"","neve_meta_disable_title":"","footnotes":""},"categories":[292],"tags":[],"class_list":["post-8561","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-answers"],"_links":{"self":[{"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/posts\/8561","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/users\/19"}],"replies":[{"embeddable":true,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/comments?post=8561"}],"version-history":[{"count":14,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/posts\/8561\/revisions"}],"predecessor-version":[{"id":11887,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/posts\/8561\/revisions\/11887"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/media\/10981"}],"wp:attachment":[{"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/media?parent=8561"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/categories?post=8561"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/tags?post=8561"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}